更新于:

分布式锁

目录

分布式锁

yudao-spring-boot-starter-protection (opens new window) 技术组件,使用 Redis 实现分布式锁的功能,它有 2 种使用方式:

Redis 分布式锁的实现原理?

参见 《Redis 实现原理与源码解析系列》 (opens new window) 文章。

# 1. 编程式锁

1
2
3
4
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>

# 1.1 Redisson 配置

无需配置。因为在 Redis 缓存 中,进行了 Spring Data Redis + Redisson 的配置。

# 1.2 实战案例

yudao-module-pay 模块的 notify ( opens new window) 功能,使用到分布式锁,确保每个 支付通知任务有且仅有一个在执行。下面,来看看这个案例是如何实现的。

友情提示:

建议你已经阅读过 《开发指南 —— Redis 缓存》 文档。

① 在 RedisKeyConstants ( opens new window) 类中,定义通知任务使用的分布式锁的 Redis Key。如下图所示:

PAY_NOTIFY_LOCK

② 创建 PayNotifyLockRedisDAO ( opens new window) 类,使用 RedisClient 实现分布式锁的加锁与解锁。如下图所示:

PayNotifyLockRedisDAO

③ 在 PayNotifyServiceImpl ( opens new window) 执行指定的支付通知任务时,通过 PayNotifyLockRedisDAO 获得分布式锁。如下图所示:

PayNotifyLockRedisDAO

技术选型:为什么不使用 Lock4j 提供的 LockTemplate 实现编程式锁?

两者各有优势,选择 Redisson 主要考虑它支持的 Redis 分布式锁的类型较多:可靠性较高的红锁、性能较好的读写锁等等。

Lock4j 的 LockTemplate 也是不错的选择,一方面不强依赖 Redisson 框架,一方面支持 ZooKeeper 等等。

# 2. 声明式锁

1
2
3
4
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>lock4j-redisson-spring-boot-starter</artifactId>
</dependency>

# 2.1 Lock4j 配置

application-local.yaml ( opens new window) 配置文件中,通过 lock4j 配置项,添加 Lock4j 全局默认的分布式锁配置。如下图所示:

配置文件

# 2.2 使用案例

在需要使用到分布式锁的方法上,添加 @Lock4j 注解,非常方便。示例代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Service
public class DemoService {

// 默认使用 lock4j 配置项
@Lock4j
public void simple() {
//do something
}

// 完全配置,支持 Spring EL 表达式
@Lock4j(keys = {"#user.id", "#user.name"}, expire = 60000, acquireTimeout = 1000)
public User customMethod(User user) {
return user;
}

}
上次更新: 2022/04/22, 22:48:53

本站由 钟意 使用 Stellar 1.25.0 主题创建。
又拍云 提供CDN加速/云存储服务
vercel 提供托管服务
湘ICP备2023019799号-1
总访问 次 | 本页访问