最近项目中要用到redis的分布式锁,参考了网上整合jedis的资料,但运行时候会各种报错。重新整理下复制直接可用。
- maven导入相关包:
redis.clients jedis2.9.0
- 新建 classpath:property/redis.properties
#最大分配的对象数 redis.pool.maxActive=200 #最大能够保持idel状态的对象数 redis.pool.maxIdle=50 redis.pool.minIdle=10 redis.pool.maxWaitMillis=20000 #当池内没有返回对象时,最大等待时间 redis.pool.maxWait=300 #格式:redis://:[密码]@[服务器地址]:[端口]/[db index] #redis.uri = redis://:12345@127.0.0.1:6379/0 redis.host = 127.0.0.1 redis.port = 6379 redis.timeout=30000 redis.password = redis.database = 0
- 新建配置文件 spring-jedis.xml 内容如下
${redis.pool.maxActive} ${redis.pool.maxIdle} - 创建工具类
@Service
public class JedisFactory {
private JedisFactory(){}
@Autowired
private JedisPool jedisPool;
private static Jedis jedis;
public Jedis getJedis() {
//从JedisPool Jedis实例
if(jedis == null){
jedis = jedisPool.getResource();
}
return jedis;
}
}
-
redis分布式锁
@Service
public class DistributedLock {
@Autowired
private JedisFactory JedisFactory;
public String occupyDistributedLock(String lockKey) {
//获得jedis实例
Jedis jedis = JedisFactory.getJedis();
//锁id(必须拥有此id才能释放锁)
String lockId = UUID.randomUUID().toString();
//占用锁同时设置失效时间 EX = seconds;秒 PX = milliseconds 毫秒
String isSuccees = jedis.set(lockKey, lockId, "NX","PX", 15000);
//占用锁成功返回锁id,否则返回null
if("OK".equals(isSuccees)){
return lockId;
}else{
return null;
}
}
public void releaseDistributedLock(String lockKey,String lockId) {
if(lockId != null){
//获得jedis实例
Jedis jedis = JedisFactory.getJedis();
//执行Lua代码删除lockId匹配的锁
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(lockId));
}
}
}
- 业务代码。省了controller部分。
@Autowired
private DistributedLock jedisLock;
@RequestMapping(value = "test", method = RequestMethod.POST)
public void test() {
String key = "key";
String lockId = null;
try {
//用redis分布式锁。
lockId = jedisLock.occupyDistributedLock(key);
if (lockId != null) {
//业务代码
System.out.println("test");
}
} catch (Exception e) {
e.printStackTrace();
log.error(e);
throw e;
} finally {
//释放锁
jedisLock.releaseDistributedLock(key, lockId);
}
}
参考:https://www.cnblogs.com/red-code/p/6657517.html



