🍅3. 集成分布式锁Redisson
选中新版正文中的对应文字,然后点“定位到这里”。
1. 添加依赖
org.redisson
redisson-spring-boot-starter
3.16.2
2. 添加配置
# 在nacos的pmhub-workflow中添加配置,配置 Redisson单机模式
redisson:
codec: org.redisson.codec.JsonJacksonCodec
threads: 4
netty:
threads: 4
single-server-config:
address: "redis://localhost:6379"
password: null
database: 0
3. RedissonConfig
/**
* @author canghe
* @description RedissonConfig
* @create 2024-06-18-16:36
*/
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
// 如果redis部署在线上就填服务器IP地址
.setAddress("redis://localhost:6379")
.setDatabase(0);
return Redisson.create(config);
}
}
4. 定义ILock锁对象
package com.laigeoffer.pmhub.base.security.pojo;
import com.laigeoffer.pmhub.base.security.service.redisson.IDistributedLock;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Objects;
@AllArgsConstructor
public class ILock implements AutoCloseable {
/**
* 持有的锁对象
*/
@Getter
private Object lock;
/**
* 分布式锁接口
*/
@Getter
private IDistributedLock distributedLock;
@Override
public void close() throws Exception {
if (Objects.nonNull(lock)) {
distributedLock.unLock(lock);
}
}
}
5. 定义IDistributedLock分布式锁接口
import com.laigeoffer.pmhub.base.security.pojo.ILock;
import java.util.concurrent.TimeUnit;
/**
* @author canghe
* @description IDistributedLock 分布式锁接口
* @create 2024-06-17-10:23
*/
public interface IDistributedLock {
/**
* 获取锁,默认30秒失效,失败一直等待直到获取锁
*
* @param key 锁的key
* @return 锁对象
*/
ILock lock(String key);
/**
* 获取锁,失败一直等待直到获取锁
*
* @param key 锁的key
* @param lockTime 加锁的时间,超过这个时间后锁便自动解锁; 如果lockTime为-1,则保持锁定直到显式解锁
* @param unit {@code lockTime} 参数的时间单位
* @param fair 是否公平锁
* @return 锁对象
*/
ILock lock(String key, long lockTime, TimeUnit unit, boolean fair);
/**
* 尝试获取锁,30秒获取不到超时异常,锁默认30秒失效
*
* @param key 锁的key
* @param tryTime 获取锁的最大尝试时间
* @return
* @throws Exception
*/
ILock tryLock(String key, long tryTime) throws Exception;
/**
* 尝试获取锁,获取不到超时异常
*
* @param key 锁的key
* @param tryTime 获取锁的最大尝试时间
* @param lockTime 加锁的时间
* @param unit {@code tryTime @code lockTime} 参数的时间单位
* @param fair 是否公平锁
* @return
* @throws Exception
*/
ILock tryLock(String key, long tryTime, long lockTime, TimeUnit unit, boolean fair) throws Exception;
/**
* 解锁
*
* @param lock
* @throws Exception
*/
void un...未能定位到原文的划线
已加入星球,可直接知识星球授权登录
二哥编程星球目前包含:
企业级Agent工作流编排项目PaiFlow
Vibe Coding版本的PaiAgent
派聪明RAG AI知识库Java版本+Go版本
微服务 PmHub、技术派、MYDB
求职派JobClaw(OpenClaw/Hermes架构
PaiCLI(类似Claude Code的Agent
派简历(代码已完成)
等实战项目。
企业级Agent工作流编排项目PaiFlow
Vibe Coding版本的PaiAgent
派聪明RAG AI知识库Java版本+Go版本
微服务 PmHub、技术派、MYDB
求职派JobClaw(OpenClaw/Hermes架构
PaiCLI(类似Claude Code的Agent
派简历(代码已完成)
等实战项目。
1. 微信扫右侧的优惠券加入知识星球
2. 解锁星球的实战项目教程和源码: 项目源码+教程获取
真诚点赞 诚不我欺
回复