@Component
public class redisLock {
Logger logger= LoggerFactory.getLogger(RedisLock.class);
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";//NX是毫秒,EX是秒
private static final String SET_WITH_EXPIRE_TIME = "PX";
創(chuàng)新互聯(lián)建站是一家集網(wǎng)站建設(shè),興寧企業(yè)網(wǎng)站建設(shè),興寧品牌網(wǎng)站建設(shè),網(wǎng)站定制,興寧網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,興寧網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
/**
* 嘗試獲取分布式鎖
* @param lockKey 鎖
* @param requestId 請求標(biāo)識
* @param expireTime 超期時間
* @return 是否獲取成功
*/
public boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
Jedis jedis=null;
try{
jedis = Const.jedisPoolCommon.getResource();
String result =jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
}catch (Exception ex){
logger.error("tryGetDistributedLock異常"+ex);
}finally {
if(jedis!=null){
jedis.close();
}
}
return false;
}
private static final Long RELEASE_SUCCESS = 1L;
/**
* 釋放分布式鎖
* @param lockKey 鎖
* @param requestId 請求標(biāo)識
* @return 是否釋放成功
*/
public boolean releaseDistributedLock( String lockKey, String requestId) {
Jedis jedis = null;
try{
jedis=Const.jedisPoolCommon.getResource();
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(lockKey), Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
}catch (Exception ex){
logger.error("releaseDistributedLock異常"+ex);
}finally {
if(jedis!=null){
jedis.close();
}
}
return false;
}
}