redisssion 工具类
引入jar包
<redisson.version>3.13.4</redisson.version> <dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>${redisson.version}</version> </dependency>
//配置项
public class RedissonManager { private static Config config = new Config(); //声明redisso对象 private static Redisson redisson = null; //实例化redisson static{ config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("xxxx"); //得到redisson对象 redisson = (Redisson) Redisson.create(config); } //获取redisson对象的方法 public static Redisson getRedisson(){ return redisson; }
//加锁
@Slf4j public class DistributedRedisLock { //从配置项获取redisson对象 private static final Redisson redisson = RedissonManager.getRedisson(); private static final String LOCK_TITLE = "REDIS_LOCK_"; //加锁 public static boolean acquire(String lockName) { //声明key对象 String key = LOCK_TITLE + lockName; //获取锁对象 RLock lock = redisson.getLock(key); lock.lock(); //lock.lock(10,TimeUnit.SECONDS); 这种是10秒后锁自动过期,不会有自动续期的机制 //boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS); 尝试加锁,最多等待100秒,上锁以后10秒自动解锁 log.info("加锁lock--------------------------------->" + Thread.currentThread().getName()); //加锁成功 return true; }
//锁的释放
public static void release(String lockName) { //必须是和加锁时的同一个key String key = LOCK_TITLE + lockName; //获取所对象 RLock lock = redisson.getLock(key); //释放锁(解锁) lock.unlock(); log.info("释放锁unlock--------------------------------->" + Thread.currentThread().getName()); } }