首先,需要在 pom.xml 中引入 Redis 的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
然后,在 application.yml 中配置 Redis 连接信息:
spring:
redis:
host: localhost
port: 6379
接下来,定义 StringRedisTemplate 类型的 bean,并在其中配置分布式锁的相关信息:
@Configuration
public class RedisConfig {
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
// 设置锁的过期时间
template.setDefaultSerializer(new GenericToStringSerializer<>(Object.class));
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
return template;
}
}
然后,在业务逻辑中使用分布式锁的方式如下:
```java @Autowired private StringRedisTemplate stringRedisTemplate;
// 定义锁的名称 private static final String LOCK_NAME = "task_lock";
// 定义锁的过期时间 private static final long LOCK_EXPIRE_TIME = 10 * 1000;
public void completeTask(String userId) { // 尝试获取锁 boolean lockAcquired = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_NAME, userId, Duration.ofMillis(LOCK_EXPIRE_TIME)); if (!lockAcquired) { // 如果获取锁失败,说明当前有其他线程正在使用锁,则不进行后续操作 return; } try { // 获取锁成功,执行具体的业务逻辑 // 获取当天完成任务的次数 String taskCountKey = "task_count_" + userId + "_