1、加入依赖
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.6</version>
</dependency>
2、装配RedissonClient。
package com.yt.service.zutil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissonConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private Integer port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.database}")
private Integer database;
@Bean
public RedissonClient getRedisson() {
Config config = new Config();
config.useSingleServer().setAddress(String.format("redis://%s:%s", host, port)).setPassword(password).setDatabase(database);
RedissonClient client = Redisson.create(config);
RedissonLockUtil.redissonClient = client;
return client;
}
}
3、封装Redisson工具类。
package com.common.redis.service;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;
public class RedissonLockUtil{
public static RedissonClient redissonClient;
public static RLock lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
return lock;
}
public static RLock tryLock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.tryLock();
return lock;
}
public static RLock tryLock(String lockKey, long waitTime, TimeUnit unit) throws InterruptedException {
unit = unit == null ? TimeUnit.SECONDS : unit;
RLock lock = redissonClient.getLock(lockKey);
lock.tryLock(waitTime, unit);
return lock;
}
public static RLock tryLock(String lockKey, long waitTime, long unlockTime) throws InterruptedException {
RLock lock = redissonClient.getLock(lockKey);
lock.tryLock(waitTime, unlockTime, TimeUnit.SECONDS);
return lock;
}
public static RLock lock(String lockKey, int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, TimeUnit.SECONDS);
return lock;
}
public static void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
if (null != lock && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
4、直接使用RedissonLockUtil工具类就可以了。
public void doSomeThing() {
try {
RedissonLockUtil.lock("redissonLock");
} finally {
RedissonLockUtil.unlock("redissonLock");
}
}