springboot配置集成RedisTemplate和Redisson,使用分布式锁案例
在Spring Boot中配置RedisTemplate
和Redisson
用于分布式锁的示例代码如下:
- 添加依赖到
pom.xml
:
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Redisson -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.16.2</version> <!-- 请使用最新版本 -->
</dependency>
- 配置
RedisTemplate
和RedissonClient
:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(lettuceConnectionFactory);
return template;
}
@Bean
public RedissonClient redissonClient(LettuceConnectionFactory lettuceConnectionFactory) {
// 使用Lettuce客户端连接
RedissonClient redissonClient = Redisson.create(Config.fromJSON(
"{\"singleServerConfig\":{\"address\":\"redis://127.0.0.1:6379\",\"clientType\":\"LETTUCE\"}}"
));
return redissonClient;
}
}
- 使用
RedissonClient
获取分布式锁:
@Service
public class DistributedLockService {
@Autowired
private RedissonClient redissonClient;
public void lockWithRedisson() {
// 获取锁对象
RLock lock = redissonClient.getLock("myLock");
try {
// 尝试加锁,最多等待100秒,锁定后最多持有锁10秒
boolean isLocked = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (isLocked) {
// 业务逻辑
System.out.println("Lock acquired");
} else {
System.out.println("Lock not acquired");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 释放锁
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
在这个例子中,我们配置了RedisTemplate
和RedissonClient
。RedisTemplate
用于非锁相关的操作,而RedissonClient
用于获取分布式锁对象。在DistributedLockService
服务中,我们使用RedissonClient
获取一个锁对象,并尝试加锁。加锁成功后执行业务逻辑,执行完毕后释放锁。
评论已关闭