# Redisson分布式锁集成2.4+ >[info] 采用redisson实现分布式锁,应用场景:秒杀、团购、购买火车票等系列高并发应用。 > 示例代码:`jeecg-cloud-module\jeecg-cloud-test\jeecg-cloud-test-more` [TOC] ## 第一步. 引入分布式锁依赖 ~~~ <!-- 引入分布式锁依赖 --> <dependency> <groupId>org.jeecgframework.boot</groupId> <artifactId>jeecg-boot-starter-lock</artifactId> </dependency> ~~~ ## 第二步. 编写分布式锁测试demo 通过jeecg自定义的注解 `@JLock` `@JRepeat` 来实现 ~~~ /** * 分布式锁测试demo */ @Slf4j @Component public class DemoLockTest { @Autowired RedissonLockClient redissonLock; /** *注解方式测试分布式锁 */ @Scheduled(cron = "0/5 * * * * ?") @JLock(lockKey= "redis-lock") public void execute() throws InterruptedException { log.info("执行execute任务开始,休眠三秒"); Thread.sleep(3000); System.out.println("=======================业务逻辑1============================="); log.info("execute任务结束,休眠三秒"); } /** * 编码方式测试分布式锁 */ @Scheduled(cron = "0/10 * * * * ?") public void execute2() throws InterruptedException { if (redissonLock.tryLock("redisson", -1, 10000)) { log.info("执行任务execute2开始,休眠三秒"); Thread.sleep(3000); System.out.println("=======================业务逻辑2============================="); log.info("定时execute2结束,休眠三秒"); redissonLock.unlock("redisson"); } else { log.info("execute2获取锁失败"); } } } ~~~ ## 分布式锁注解 `@JLock` 示例: ~~~ //lockKey支持spel表达式 @JLock(lockKey= "redis-lock") @JLock(lockKey="#user.name") @JLock(lockKey ={"#user.name","#user.id"}) ~~~ 参数说明: - [JLock 参数定义](https://gitee.com/jeecg//jeecg-boot-starter/blob/master/jeecg-boot-starter-lock/src/main/java/org/jeecg/boot/starter/lock/annotation/JLock.java) ## 防止重复提交的注解 `@JRepeat` 示例: ~~~ @JRepeat(lockKey = "#name", lockTime = 5) ~~~ 参数说明: - [JRepeat 参数定义](https://gitee.com/jeecg/jeecg-boot-starter/blob/master/jeecg-boot-starter-lock/src/main/java/org/jeecg/boot/starter/lock/annotation/JRepeat.java) ## 第三步. 分布式锁redisson配置 分布式锁配置在nacos中jeecg-dev.yaml里 ![](https://img.kancloud.cn/42/38/4238241fa3f1709eccab2bb07a3f558b_813x678.png) - address:连接地址和端口 - password:redis密码 - type:redis部署方式 - enabled:是否启用分布式锁 支持单机、哨兵、集群、主从4中redis部署方式 ### 1单机配置示例 ~~~ redisson.address=127.0.0.1:6379 redisson.type=STANDALONE ~~~ ### 2 哨兵配置示例 **redisson.lock.server.address**格式为: sentinel.conf配置里的sentinel别名,sentinel1节点的服务IP和端口,sentinel2节点的服务IP和端口,sentinel3节点的服务IP和端口 比如sentinel.conf里配置为sentinel monitor my-sentinel-name 127.0.0.1 6379 2,那么这里就配置my-sentinel-name ~~~ redisson.address=my-sentinel-name,127.0.0.1:26379,127.0.0.1:26389,127.0.0.1:26399 redisson.type=SENTINEL ~~~ ### 3 集群配置示例 cluster方式至少6个节点(3主3从,3主做sharding,3从用来保证主宕机后可以高可用) 地址格式为: 127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384 ~~~ redisson.address=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384 redisson.type=CLUSTER ~~~ ### 4 主从配置示例 比如:127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381 代表主节点:127.0.0.1:6379,从节点127.0.0.1:6380,从127.0.0.1:6381 ~~~ redisson.address=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381 redisson.type=MASTERSLAVE ~~~