一、引入maven依赖
class="java"><dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.16.RELEASE</version>
</dependency>
二、spring-data-jedis命令封装
private StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
public Object eval(final String script, final List<String> keys, final List<String> args) {
return stringRedisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection connection) {
Jedis jedis = (Jedis) connection.getNativeConnection();
return jedis.eval(script, keys, args);
}
}, true);
}
public String set(final String key, final String value, final String nxxx, final String expx, final long time) {
return stringRedisTemplate.execute(new RedisCallback<String>() {
public String doInRedis(RedisConnection connection) {
Jedis jedis = (Jedis) connection.getNativeConnection();
return jedis.set(key, value, nxxx, expx, time);
}
}, true);
}
三、分布式锁封装
private static final String LOCK_SUCCESS = "OK";
private static final String IF_ABSENT = "NX";
// private static final String NOT_ABSENT = "XX";
private static final String EXPIRE_TIME_PX = "PX"; // 毫秒
// private static final String EXPIRE_TIME_EX = "EX"; // 秒
private static final Long RELEASE_SUCCESS = 1L;
/**
* 尝试获取分布式锁
*
* @param key
* @param requestId 请求ID
* @param expired
* @return
*/
protected boolean tryLock(String key, String requestId, long expired) {
String result = stringRedisTemplate.set(key, requestId, IF_ABSENT, EXPIRE_TIME_PX, expired);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
return false;
}
/**
* 释放分布式锁
*
* @param key
* @param requestId 请求ID
* @return
*/
protected boolean unlock(String key, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = stringRedisTemplate.eval(script, Collections.singletonList(key), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
return false;
}