欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Spring Boot使用Redis实现分布式锁

Spring Boot使用Redis实现分布式锁

2025/9/25 0:16:09 来源:https://blog.csdn.net/ghie9090/article/details/148395204  浏览:    关键词:Spring Boot使用Redis实现分布式锁

在分布式系统中,分布式锁是一种解决并发问题的常用技术。Redis由于其高性能和丰富的特性,成为实现分布式锁的理想选择。本文将详细介绍如何在Spring Boot应用中使用Redis实现分布式锁。

一、环境准备

  1. 安装Redis:确保已经安装并运行Redis服务。
  2. Spring Boot项目:确保已经创建并配置好了Spring Boot项目。
  3. 添加依赖:在 pom.xml中添加Spring Data Redis和Lettuce依赖。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency><groupId>io.lettuce.core</groupId><artifactId>lettuce-core</artifactId>
</dependency>
​

二、Redis配置

在 application.properties或 application.yml文件中配置Redis连接信息。

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword # 如果Redis设置了密码
​

三、实现分布式锁

1. 创建Redis配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;@Configuration
public class RedisConfig {@Beanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {return new StringRedisTemplate(factory);}@Beanpublic ValueOperations<String, String> valueOperations(StringRedisTemplate stringRedisTemplate) {return stringRedisTemplate.opsForValue();}
}
​
2. 创建分布式锁工具类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;@Component
public class RedisLock {@Autowiredprivate ValueOperations<String, String> valueOperations;private static final long LOCK_EXPIRE = 30L; // 锁过期时间,30秒private static final String LOCK_VALUE = "LOCKED";public boolean lock(String key) {Boolean success = valueOperations.setIfAbsent(key, LOCK_VALUE, LOCK_EXPIRE, TimeUnit.SECONDS);return success != null && success;}public void unlock(String key) {valueOperations.getOperations().delete(key);}
}
​
3. 使用分布式锁
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class LockController {@Autowiredprivate RedisLock redisLock;@GetMapping("/lock")public String lock() {String key = "myLock";if (redisLock.lock(key)) {try {// 业务逻辑Thread.sleep(2000); // 模拟业务处理时间return "Locked and processed";} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally {redisLock.unlock(key);}} else {return "Failed to acquire lock";}return "Unexpected error";}
}
​

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词