Redis使用


 ValueOperations vo=stringRedisTemplate.opsForValue();
  
  //jedis
  Jedis jedis = new Jedis("localhost",6379);
  
  //管道,相当于异步,非常快速
     Pipeline pipeline = jedis.pipelined();
     long start = System.currentTimeMillis();
     pipeline.watch("p");
     //管道中调用事物
     pipeline.multi();
 /* hash操作
  *   HashMap hash=new HashMap<>();
     hash.put("field1", "hello");
     hash.put("field2", "world");
     pipeline.hmset("myhash", hash);*/
//     pipeline.hdel("myhash", "field1","field2");
    
 /*  List(列表)
     pipeline.lpush("runoob", "redis1");
     pipeline.lpush("runoob", "redis2");
     pipeline.lpush("runoob", "redis3");
     pipeline.lpush("runoob", "redis1","redis2","redis3","redis4","redis5");
  *    */
    
     /*set列表
     pipeline.sadd("sunoob", "redis1","redis2","redis3");*/
    
   /*  zset(sorted set:有序集合) 
     pipeline.zadd("zunoob", 0, "redis1");
     pipeline.zadd("zunoob", 1, "redis2");*/
   /*  String
    * for (int i = 0; i < 100000; i++) {
           pipeline.set("p" + i, "p" + i);
           //设置时间
           pipeline.expire("p" + i, Integer.parseInt(String.valueOf(lockTime)));
//         pipeline.del("p" + i);
     } */
     //管道中执行事物
     pipeline.exec();
     List<Object> results = pipeline.syncAndReturnAll();
     long end = System.currentTimeMillis();
     System.out.println("Pipelined SET: " + ((end - start)/1000.0) + " seconds");
     jedis.disconnect();
 }
 
 /* 实现分布式锁的条件
  * 1.互斥性。在任意时刻,只有一个客户端能持有锁。
 2.不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
 3.具有容错性。只要大部分的Redis节点正常运行,客户端就可以加锁和解锁。
 4.解铃还须系铃人。加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。*/
 
 //加锁操作
 @RequestMapping(value="/doLockRedis",method=RequestMethod.GET)
  public static boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
    Jedis jedis = new Jedis("localhost",6379);
    //nx表示只有键不存在时,才对键进行设置,相当于setnx,注意expireTime是毫秒
         String result = jedis.set(lockKey, requestId, "NX", "PX", expireTime);
         if (LOCK_SUCCESS.equals(result)) {
             return true;
         }
         return false;
  }
 
 //解锁操作
 @RequestMapping(value="/doUnLockRedis",method=RequestMethod.GET)
 public Boolean doUnLockRedis(String lockKey, String requestId)  throws Exception{
  Jedis jedis = new Jedis("localhost",6379);
  //使用eval使其具有原子性
  String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  Object result2 = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId)); 
  //     System.out.println(result2);1
     if (RELEASE_SUCCESS.equals(result2)) {
          return true;
     }  
     return false;   
 }
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值