下面的分布式锁分别是利用JedisPool 和Redisson 实现的,可以选择行使用。其中方法的命名匹配的为一类,希望可以帮助大家!
代码语言:javascript复制package com.utils;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* @des 分布式锁,下面有两种方式实现
* @author 719383495@qq.com
* @date 2019/7/31 15:50
*/
@Component
public class RedisUtil {
private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final String DEFAULT_VALUE = "V";
@Resource
private JedisPool jedisPool;
@Resource
private Redisson redisson;
/***
* @desc lock
* @param redisKey
* @param waitTime
* @param timeout
* @return
*/
public boolean addRedisLock(String redisKey, long waitTime, long timeout) {
RLock lock = redisson.getLock(redisKey);
try {
// 尝试加锁,等待时间之内加锁,加锁之后timeout之间内自动解锁
boolean result = lock.tryLock(waitTime, timeout, TimeUnit.MILLISECONDS);
if (result) {
return true;
}
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
return false;
}
public void delRedisLock1(String redisKey) {
redisson.getLock(redisKey).unlock();
}
public Jedis getJedis() {
return jedisPool.getResource();
}
/***
* @desc redis's set and del operation to lock
* @param redisKey
* @param timeout
* @return
*/
public boolean addRedisLock(String redisKey, long timeout) {
try (Jedis jedis = getJedis()) {
if ("".equals(redisKey) || null == redisKey) {
return false;
}
String result = jedis.set(redisKey, DEFAULT_VALUE, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, timeout);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return false;
}
public void delRedisLock(String redisKey) {
try {
Jedis jedis = getJedis();
if (!"".equals(redisKey)) {
Long del = jedis.del(redisKey);
logger.info("锁名:{}, 释放锁是否成功:{}", redisKey, del);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
}
}