package redis.redis;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;/** * 描述:Jedis连接池工具类 * 【时间 2019-05-20 15:13:34 作者 陶攀峰】 */public class JedisPoolUtil { private static volatile JedisPool jedisPool=null; private JedisPoolUtil() {} /** * 描述:获取 * 【时间 2019-05-21 11:02:24 作者 陶攀峰】 */ public static JedisPool getJeidPoolInstance() { if (jedisPool==null) { synchronized (JedisPoolUtil.class) { if (jedisPool==null) { jedisPool=new JedisPool("192.168.37.160",6379); } } } return jedisPool; } /** * 描述:关闭 * 【时间 2019-05-21 11:02:13 作者 陶攀峰】 */ public static void close(JedisPool jedisPool,Jedis jedis) { if (jedis!=null) { jedisPool.returnResourceObject(jedis); } } }
package redis.redis;import redis.clients.jedis.BinaryClient.LIST_POSITION;import java.util.HashMap;import java.util.Map;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.Transaction;/** * 描述:操作数据库 * 【时间 2019-05-20 15:28:46 作者 陶攀峰】 */public class Redis_Test { public static void main(String[] args) { JedisPool jedisPool=JedisPoolUtil.getJeidPoolInstance(); Jedis jedis=null; try { jedis=jedisPool.getResource();//获取 System.out.println("连接:"+jedis.ping());//测试连接性 正常返回PONG transaction(jedis);//事务 basics(jedis);//基础操作 } catch (Exception e) { e.printStackTrace(); }finally { //关闭 JedisPoolUtil.close(jedisPool, jedis); } } /** * 描述:Redis事务 * 【时间 2019-05-20 15:33:59 作者 陶攀峰】 */ public static void transaction(Jedis jedis){ int k3=10; jedis.watch("k1"); //Thread.sleep(7000); if (Integer.parseInt(jedis.get("k1"))map=new HashMap<>(); map.put("id","13"); map.put("name", "daniu"); map.put("sex", "nan"); jedis.hmset("stu", map); System.out.println(jedis.hmget("stu", "id","name","sex")); System.out.println(jedis.hgetAll("stu")); System.out.println(jedis.hdel("stu", "id","sex2"));//返回删除的数量 System.out.println(jedis.hlen("stu")); System.out.println(jedis.hexists("stu", "name"));//存在true 不存在false System.out.println(jedis.hkeys("stu")); System.out.println(jedis.hvals("stu")); System.out.println(jedis.hincrBy("stu", "id", 2));//每次增加2 返回增加后的数值 System.out.println(jedis.hincrByFloat("stu", "id", 3.4));//每次增加3.4 返回增加后的数值 System.out.println(jedis.hsetnx("stu", "id1", "99"));//插入成功返回1 失败返回0 //-------------------Zset-------------------- jedis.zadd("zs1", 60, "v1"); jedis.zadd("zs1", 70, "v2"); jedis.zadd("zs1", 80, "v3"); jedis.zadd("zs1", 90, "v4"); jedis.zadd("zs1", 100, "v5"); System.out.println(jedis.zrange("zs1", 0, -1)); System.out.println(jedis.zrangeByScore("zs1", 60, 90));//60<=score<=90的value值 System.out.println(jedis.zrem("zs1", "v5","v6"));//返回删除记录数 System.out.println(jedis.zcard("zs1"));//返回数量 System.out.println(jedis.zcount("zs1", 60, 80));//60<=score<=80的数量 System.out.println(jedis.zrank("zs1", "v4"));//返回所在位置下标 System.out.println(jedis.zscore("zs1", "v1"));//返回v1的score //zre表示把原本的数据逆转顺序之后,再读取,不改变原有数据 System.out.println(jedis.zrevrank("zs1", "v4")); System.out.println(jedis.zrevrange("zs1", 0, -1)); } }