在springboot项目中使用redis实现锁
在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: localhostport: 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:";@Autowiredprivate 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 {@Autowiredprivate 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的分布式锁。