前段时间在kubernetes中做多副本部署时,发现有些服务中存在定时任务,这样一来不同副本都会执行这些定时任务,导致任务重复执行,然后找了一下决定使用 Redisson 来做这个,其实现在来看分布式时锁相对容易多了,就是在同一时刻去获取一把锁,拿到这把锁就可以进行操作,拿不到就不能操作,这里 Redisson 是利用在 Redis 存放一个 Key (其实是setNX)来做这个工作。当然定时任务仅仅分布式锁运用的一种场景。现在 Redisson 的使用也简单了很多,官方直接提供了 redisson-spring-boot-starter
,和SpringBoot整合也很方便,下面是集成示例:
1. 引入依赖
注:redisson-spring-data 需要根据项目中使用的 SpringBoot 的版本进行重选,3.11.5 版本默认引用的是 redisson-spring-data-21(即适用于SpringBoot版本为2.1.x的使用),但项目中我的SpringBoot是2.0.7就不行,需要选用redisson-spring-data-20
,不做这一步启动会出错的,具体的pom依赖为:
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-data-20</artifactId>
<version>3.11.5</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.11.5</version>
<exclusions>
<exclusion>
<artifactId>redisson-spring-data-21</artifactId>
<groupId>org.redisson</groupId>