参考🔗,该文解释的很详细,非常👍 Redis 分布式锁的正确实现方式( Java 版 )
记录我的实际应用Code,redis的连接要随时释放哦
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import javax.annotation.Resource;
import java.util.Collections;
/**
* @author 醉卧花海听萧
* @date 2019/5/6
*/
@Slf4j
@Component
public class SpaceRedisService {
private static final String LOCK_SUCCESS = "OK";
private static final Long RELEASE_SUCCESS = 1L;
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
@Resource(name = "redisTemplate1")
private RedisTemplate redisTemplate1;
public Boolean lock(String key, String requestId, long expireTime) {
RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate1.getConnectionFactory());
Jedis jedis = (Jedis) conn.getNativeConnection();
try {
String result = jedis.set(key, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
log.error("--LOCK ERROR:", e);
} finally {
RedisConnectionUtils.releaseConnection(conn, redisTemplate1.getConnectionFactory());
}
return false;
}
public Boolean unLock(String key, String requestId) {
RedisConnection conn = RedisConnectionUtils.getConnection(redisTemplate1.getConnectionFactory());
Jedis jedis = (Jedis) conn.getNativeConnection();
try {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
log.error("--UNLOCK ERROR:", e);
} finally {
RedisConnectionUtils.releaseConnection(conn, redisTemplate1.getConnectionFactory());
}
return false;
}
}
网友评论