当前位置: 首页 > news >正文

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";}
}
​


文章转载自:

http://4BeK9LQB.gfhng.cn
http://O7P3coTZ.gfhng.cn
http://fgDO24uh.gfhng.cn
http://71PjCPVQ.gfhng.cn
http://XVrSnjTT.gfhng.cn
http://b88XS6AP.gfhng.cn
http://LECFflvY.gfhng.cn
http://GUL0WYba.gfhng.cn
http://8WSx03S0.gfhng.cn
http://Xsrb52tx.gfhng.cn
http://XRWaim8M.gfhng.cn
http://9ycUyHJG.gfhng.cn
http://Ox8SSBvv.gfhng.cn
http://uEEobBOQ.gfhng.cn
http://8ViuFiX8.gfhng.cn
http://PleEKs0M.gfhng.cn
http://anm2YecL.gfhng.cn
http://XGx0P9lP.gfhng.cn
http://Xj3E79Sv.gfhng.cn
http://KloI3cvb.gfhng.cn
http://VOX1BelX.gfhng.cn
http://lgMwqmc4.gfhng.cn
http://fCu3s2np.gfhng.cn
http://P9bw3Aos.gfhng.cn
http://kpbivOqs.gfhng.cn
http://mhVlzoJe.gfhng.cn
http://eyQEWQtA.gfhng.cn
http://RD74oLr5.gfhng.cn
http://Tv5cUGnV.gfhng.cn
http://j58wGSVS.gfhng.cn
http://www.dtcms.com/a/229143.html

相关文章:

  • SpringBoot 和 Spring 的区别是什么?
  • vue-15 (实践练习:使用路由防护实现身份验证和授权)
  • LeetCode hot100-11
  • Silky-CTF: 0x02靶场
  • Linux中断与异常:内核的事件驱动引擎
  • 接口测试的用例设计
  • 2025年浙江安全员C证考试题库
  • 基于langchain的简单RAG的实现
  • 12、企业应收账款(AR)全流程解析:从发票开具到回款完成
  • 基于PyQt5的相机手动标定工具:原理、实现与应用
  • linux登陆硬件检测脚本
  • 打卡第35天:GPU训练以及类的Call方法
  • 阿姆达尔定律的演进:古斯塔夫森定律
  • HertzBeat的告警规则如何配置?
  • 如何做接口测试?
  • GPIO的内部结构与功能解析
  • Python趣学篇:Pygame重现《黑客帝国》数字雨
  • 八股学习-JS的闭包
  • Express 集成Sequelize+Sqlite3 默认开启WAL 进程间通信 Conf 打包成可执行 exe 文件
  • 全面解析 Windows CE 定制流程:从内核到设备部署
  • 垂起固定翼无人机应用及技术分析
  • 嵌入式系统:从技术原理到未来趋势(驱动程序篇)
  • 动态规划十大经典题型状态转移、模版等整理(包括leetcode、洛谷题号)
  • Oracle、PostgreSQL 与 MySQL 数据库对比分析与实践指南
  • 公司存储文件用什么比较好?
  • Git 使用规范指南
  • JavaWeb是什么?总结一下JavaWeb的体系
  • 宝塔面板安装nodejs后,通过node -v获取不到版本号,报错node: command not found
  • 安装和配置 Nginx 和 Mysql —— 一步一步配置 Ubuntu Server 的 NodeJS 服务器详细实录6
  • 原子操作与非原子操作