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;
}