RedisUtil-redisTemplate-setNX

//作为普通锁
public boolean setNX(String key, String value) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
if (acquire) {
return true;
} else {
return false;
}
});
}
//重试锁
public boolean retrySetNX(String key, String value) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
Boolean acquire = connection.setNX(key.getBytes(), value.getBytes());
if (acquire) {
return true;
} else {
return retrySetNX(key, value);
}
});
}
//setNX设置有效期
//expire 单位:s
public boolean setNXAndTime(final String key, final String value, final long expire) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
Object obj = connection.execute("set", key.getBytes(), value.getBytes(), SafeEncoder.encode("NX"), SafeEncoder.encode("EX"), Protocol.toByteArray(expire));
return obj != null;
});}

posted @ 2020-12-29 09:46  DiligentCoder  阅读(863)  评论(0编辑  收藏  举报