在Spring Boot项目中使用Redis实现锁,可以借助Spring Data Redis来简化Redis操作。以下是一个详细的示例,展示如何使用Redis实现简单的分布式锁:
1. 引入依赖
在pom.xml文件中添加Spring Data Redis的依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
2. 配置Redis
在application.yml文件中配置Redis连接信息:
spring:
redis:
host: localhost
port: 6379
3. 创建Redis锁工具类
创建一个工具类来处理锁的获取和释放操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockUtil {
private static final String LOCK_PREFIX = "redis_lock:";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 尝试获取锁
*
* @param lockKey 锁的键
* @param value 当前线程的唯一标识
* @param timeout 获取锁的最大等待时间,单位秒
* @param expire 锁的过期时间,单位秒
* @return 是否获取到锁
*/
public boolean tryLock(String lockKey, String value, int timeout, int expire) {
String key = LOCK_PREFIX + lockKey;
try {
for (int i = 0; i < timeout; i++) {
// 使用setIfAbsent方法尝试设置锁,如果设置成功则获取到锁
if (redisTemplate.opsForValue().setIfAbsent(key, value)) {
// 设置锁的过期时间,防止死锁
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
return true;
}
// 等待1秒后重试
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return false;
}
/**
* 释放锁
*
* @param lockKey 锁的键
* @param value 当前线程的唯一标识
*/
public void unlock(String lockKey, String value) {
String key = LOCK_PREFIX + lockKey;
try {
// 只有当前线程设置的锁才能被释放
Object currentValue = redisTemplate.opsForValue().get(key);
if (StringUtils.hasText(currentValue) && currentValue.equals(value)) {
redisTemplate.delete(key);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. 使用Redis锁
在服务类中使用上述工具类来获取和释放锁:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
@RestController
public class ExampleController {
@Autowired
private RedisLockUtil redisLockUtil;
@GetMapping("/example")
public String exampleMethod() {
String lockKey = "example_lock";
// 使用UUID作为当前线程的唯一标识
String value = UUID.randomUUID().toString();
boolean locked = redisLockUtil.tryLock(lockKey, value, 5, 10);
if (locked) {
try {
// 模拟业务逻辑
return "获取到锁,执行临界区代码";
} finally {
redisLockUtil.unlock(lockKey, value);
}
} else {
return "未获取到锁";
}
}
}
在上述示例中:
RedisLockUtil工具类提供了tryLock和unlock方法来处理锁的获取和释放。tryLock方法尝试在指定的timeout时间内获取锁,并设置锁的过期时间为expire秒。unlock方法确保只有设置锁的线程才能释放锁,防止误释放。ExampleController展示了如何在实际的Spring Boot控制器方法中使用这些方法来保护临界区代码。
这样,通过Spring Data Redis,我们在Spring Boot项目中实现了基于Redis的分布式锁。
SpringBoot集成Redis实现分布式锁
1062

被折叠的 条评论
为什么被折叠?



