提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
环境:
spring-boot 2.4.7
一、添加pom依赖
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
</dependency>
二、 配置及测试
1. RedisConfig
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
@Bean
public RedisTemplate<String, String> strRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
StringRedisSerializer serializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(serializer);
redisTemplate.setValueSerializer(serializer);
return redisTemplate;
}
@Bean
public RedisLockRegistry redisLockRegistry(RedisConnectionFactory redisConnectionFactory) {
RedisLockRegistry redisLockRegistry = new RedisLockRegistry(redisConnectionFactory, "redis-lock", TimeUnit.MINUTES.toMillis(1));
RedisLock.init(redisLockRegistry);
return redisLockRegistry;
}
}
2. RedisLock 封装一下
@Data
public class RedisLock {
public static Logger log = LoggerFactory.getLogger(RedisLock.class);
private static RedisLockRegistry redisLockRegistry;
private Lock lock;
public static void init(RedisLockRegistry redisLockRegistry) {
RedisLock.redisLockRegistry = redisLockRegistry;
}
public boolean lock() {
lock = redisLockRegistry.obtain(this.lockKey);
return lock.tryLock();
}
public boolean tryLock(long wait, TimeUnit unit) {
lock = redisLockRegistry.obtain(this.lockKey);
try {
return lock.tryLock(wait, unit);
} catch (InterruptedException e) {
return false;
}
}
public Boolean unlock() {
lock.unlock();
return true;
}
}
3. 测试
@Test
public void test1() throws InterruptedException {
RedisLock lock = new RedisLock("test");
log.info("res1: {}", lock.lock());
new Thread(
() -> {
log.info("res1: {}", lock.tryLock(60L, TimeUnit.SECONDS));
}
)
.start();
Thread.sleep(20000);
lock.unlock();
}