package com.business.platform.service.ticket.util;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
/**
* <p>Title : RedisUtil.java</p>
* <p>Description : redis工具</p>
* <p>DevelopTools : IntelliJ IDEA 2018.2.3 x64</p>
* <p>DevelopSystem : Windows 10</p>
* <p>Company : wcy</p>
* @author : WangChenYang
* @date : 2021/5/25 10:29
* @version : 0.0.1
*/
public class RedisUtil {
private static JedisPool jedisPool = null;
static{
JedisPoolConfig jpc = new JedisPoolConfig();
jpc.setMaxTotal(100);
jedisPool = new JedisPool(jpc,"10.100.2.129",6379,5000,"123456");
}
public static Jedis getJedis(){
return jedisPool.getResource();
}
private static final String LOCK_KEY = "MARKETING_APP:LOCK:";
/**
* 分布式锁
* @Author: 王晨阳
* @Date: 2021/8/12-10:01
*/
public static boolean lock(String lockName, long acquireTimeout, long lockTimeout){
String realLockName = LOCK_KEY+lockName;
String theadId = String.valueOf(Thread.currentThread().getId());
Jedis jedis = null;
if (acquireTimeout == 0) {
//如未设置锁获取超时时间默认为10秒
acquireTimeout = 10000;
}
if (lockTimeout == 0) {
//如未设置锁超时时间默认未60秒
lockTimeout = 60000;
}
int lockTimeoutMin = (int) (lockTimeout / 1000);
long acquireEndTime = System.currentTimeMillis() + acquireTimeout;
try{
jedis = RedisConnections.getJedis();
//防止未设置时间产生死锁
if(jedis.ttl(realLockName) == -1){
jedis.expire(realLockName , lockTimeoutMin);
}
while(System.currentTimeMillis() < acquireEndTime){
//加锁成功
if(theadId.equals(jedis.get(realLockName)) || jedis.setnx(realLockName, theadId) == 1){
Log.info("线程{}获取锁成功", theadId);
jedis.expire(realLockName , lockTimeoutMin);
return true;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}finally {
jedis.close();
}
return false;
}
/**
* 当前线程 释放锁
* @Author: 王晨阳
* @Date: 2021/8/12-10:01
*/
public static boolean releaseLock(String lockName) {
String realLockName = LOCK_KEY+lockName;
String theadId = String.valueOf(Thread.currentThread().getId());
Jedis jedis = null;
boolean isRelease = false;
try {
jedis = RedisConnections.getJedis();
while (true) {
//jedis事务操作 监控realLockName 如果其中值发生变化tx.exec事务不会提交(注jedis中的事务不具备原子性,其中一个事务有错误,另外的仍然执行)
jedis.watch(realLockName);
if (theadId.equals(jedis.get(realLockName))) {
Transaction tx = jedis.multi();
tx.del(realLockName);
if (tx.exec().isEmpty()) {
continue;
}
Log.info("线程{}释放锁成功", theadId);
isRelease = true;
}
//q取消监控
jedis.unwatch();
break;
}
} finally {
jedis.close();
}
return isRelease;
}
}