Lock4j是一个分布式锁组件,它提供了多种不同的支持以满足不同性能和环境的需求,基于Spring AOP的声明式和编程式分布式锁,支持RedisTemplate、Redisson、Zookeeper。
基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
-
项目地址:https://github.com/YunaiV/ruoyi-vue-pro
-
视频教程:https://doc.iocoder.cn/video/
-
-
• 支持redission, redisTemplate, zookeeper,可混用,支持扩展。
开源地址:
https://gitee.com/baomidou/lock4j
基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能
-
项目地址:https://github.com/YunaiV/yudao-cloud
-
视频教程:https://doc.iocoder.cn/video/
<dependency>
<groupId>com.baomidougroupId>
<artifactId>lock4j-redis-template-spring-boot-starterartifactId>
<version>2.2.4version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>lock4j-redisson-spring-boot-starterartifactId>
<version>2.2.4version>
dependency>
spring:
redis:
database:0
# Redis服务器地址 写你的ip
host:127.0.0.1
# Redis服务器连接端口
port:6379
# Redis服务器连接密码(默认为空)
password:
# 连接池最大连接数(使用负值表示没有限制 类似于mysql的连接池
jedis:
pool:
max-active:200
# 连接池最大阻塞等待时间(使用负值表示没有限制) 表示连接池的链接拿完了 现在去申请需要等待的时间
max-wait:-1
# 连接池中的最大空闲连接
max-idle:10
# 连接池中的最小空闲连接
min-idle:0
# 连接超时时间(毫秒) 去链接redis服务端
timeout: 6000
package com.baomidou.lock.annotation;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public@interfaceLock4j{
Stringname()default"";
Class executor()defaultLockExecutor.class;
String[] keys()default{""};
longexpire()default-1L;
longacquireTimeout()default-1L;
booleanautoRelease()defaulttrue;
}
@RestController
@RequestMapping("/mock")
publicclassMockController{
@GetMapping("/lockMethod")
@Lock4j(keys = {"#key"}, acquireTimeout = 1000, expire = 10000)
publicResultlockMethod(@RequestParam String key){
ThreadUtil.sleep(5000);
returnResult.OK(key);
}
}
打开浏览器窗口,重复刷新访问:
http://localhost:8080/mock/lockMethod?key=123
成功获得锁访问结果:
{
"success":true,
"message":"操作成功!",
"code":200,
"result":"123",
"timestamp":1678866083211
}
抢占不到锁,Lock4j会抛出
com.baomidou.lock.exception.LockFailureException: request failed,please retry it.
异常,通过全局异常处理返回如下结果:
{
"success":false,
"message":"操作失败,request failed,please retry it.",
"code":500,
"result":null,
"timestamp":1678866034929
}
/**
* 自定义分布式锁执行器
*
* @author: austin
* @since: 2023/3/15 15:45
*/
@Component
publicclassCustomRedissonLockExecutorextendsAbstractLockExecutor{
@Override
publicObjectacquire(String lockKey, String lockValue, long expire, long acquireTimeout){
returnnull;
}
@Override
publicbooleanreleaseLock(String key, String value, Object lockInstance){
returnfalse;
}
}
在注解上直接指定特定的执行器:
@Lock4j(executor = CustomRedissonLockExecutor.class)
。
/**