Springboot Redis 分布式锁
2018-08-08 本文已影响0人
Java程序员
-
首先搭建springboot1.X 项目
-
倒入redis相关的JAR
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
-
加锁
public boolean setNx(String lockKey, String requestId, int expireTime) { boolean success = stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), requestId.getBytes(), Expiration.from(expireTime, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT)); return success; }
-
释放锁
public boolean releaseDistributedLock(String lockKey, String requestId) {
String scriptStr = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
DefaultRedisScript<Long> script = new DefaultRedisScript(scriptStr, Long.class);
List<String> keys = new ArrayList<>();
keys.add(lockKey);
Long result = stringRedisTemplate.execute(script, new StringRedisSerializer(), new RedisSerializer<Long>() {
private final Charset charset = Charset.forName("UTF8");
@Override
public byte[] serialize(Long aLong) throws SerializationException {
return (aLong == null ? null : (aLong.toString()).getBytes(charset));
}
@Override
public Long deserialize(byte[] bytes) throws SerializationException {
return (bytes == null ? null : Long.parseLong(new String(bytes, charset)));
}
}, keys, requestId);
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}