获得锁
@Autowired
@Qualifier("redisTemplate")
private RedisTemplate redisTemplate;
/**
* 获得锁
* @param lockKey
* @param requestId
* @param expireTime
* @return
*/
public boolean tryGetDistributedLock(final String lockKey, final String requestId, final int expireTime) {
return ((Boolean)this.redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
Jedis jedis = (Jedis)connection.getNativeConnection();
String result = jedis.set(lockKey, requestId, "NX", "PX", expireTime);
return "OK".equals(result);
}
})).booleanValue();
}
释放锁
/**
* 释放锁
* @param lockKey
* @param requestId
* @return
*/
public boolean releaseDistributedLock(final String lockKey, final String requestId) {
return ((Boolean) this.redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
Jedis jedis = (Jedis) connection.getNativeConnection();
Object result = jedis.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end", Collections.singletonList(lockKey), Collections.singletonList(requestId));
return "OK".equals(result);
}
})).booleanValue();
}
Redisson实现(推荐)
RLock lock = redisson.getLock("lock");
lock.lock();
try {
// do sth.
} finally {
lock.unlock();
}
其它
建议Redis3.0版本以及其以下版本使用。