基于Redisson實現(xiàn)注解式分布式鎖的示例代碼
一、背景
基于redisson的分布式鎖實現(xiàn),我們可以比較容易的控制競態(tài)資源的分布式并發(fā)控制,但是使用的時候會出現(xiàn)很多重復的try-catch-finally代碼塊,獲取鎖、加鎖和釋放鎖等,用法大致如下:
RLock lock = redissonClient.getLock("lock_name");
try {
if(lock.tryLock(5,10, TimeUnit.SECONDS)) {
//do something
}
} catch (Exception e) {
log.error("occur error",e);
} finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}寫代碼講究一個優(yōu)雅和高效,作為一個有追求的程序員,項目中出現(xiàn)大面積重復性的手動加鎖解鎖以及try-catch-finally代碼塊是不能接受的。 從鎖使用方式中,我們可以抽象出通用的部分,try-catch-finally代碼塊,以及獲取鎖、加鎖和解鎖邏輯,那么有沒有一種方式把這些邏輯抽取到一個地方管理,然后在需要使用鎖的地方,通過簡單的方式引入加鎖解鎖邏輯? 答案是可以的,我們可以結合自定義注解和切面,把加鎖邏輯封裝起來,然后攔截使用了解鎖注解的方法,把加鎖解鎖邏輯織入進去就可以了。
二、寫成starter復用
新建一個starter工程,把加鎖邏輯封裝到切面,然后通過注解的方式提供給業(yè)務使用。
1.引入依賴
引入redis和redisson相關依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
</dependency>2.定義分布式鎖注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface XLock {
String key() default "";
@AliasFor("key")
String value() default "";
long waitTime() default 5;
long leaseTime() default 30;
TimeUnit unit() default TimeUnit.SECONDS;
}定義加鎖的key,等待時間,鎖釋放時間和時間單位。
3.定義分布式鎖屬性
@ConfigurationProperties(prefix = "redisson.redis")
@Data
public class RedissonProperties {
private String port;
private String password;
private int database = 0;
/**
* redis服務端類型
* @see ServerType
*/
private Integer serverType;
private SingleServer singleServer;
private ClusterServers clusterServers;
private MasterSlaveServers masterSlaveServers;
private ReplicatedServers replicatedServers;
private SentinelServers sentinelServers;
@Data
public static class SingleServer {
private String host;
}
@Data
public static class ClusterServers {
private String hosts;//多個用逗號隔開
}
@Data
public static class MasterSlaveServers {
private String masterHost;
private String slaveHosts;//多個用逗號隔開
}
@Data
public static class ReplicatedServers {
private String hosts;
}
@Data
public static class SentinelServers {
private String masterName;
private String hosts;
}
}包含了端口,密碼,默認數(shù)據(jù)庫,以及redis server各種模式的支持。 在使用的時候需要在配置文件中添加如下類似的配置:
redisson:
redis:
port: 6379
password: xxxxxx
database: 0
serverType: 1 #2,3,4,5
singleServer:
host: 127.0.0.1
clusterServers:
hosts: 192.168.0.1,192.168.0.2,192.168.0.3
masterSlaveServers:
masterHost: 127.0.0.1
slaveHosts: 192.168.0.1,192.168.0.2
replicatedServers:
hosts: 192.168.0.1,192.168.0.2,192.168.0.3
sentinelServers:
masterName: masterNode
hosts: 192.168.0.1,192.168.0.2,192.168.0.34.編寫切面邏輯
@Slf4j
@Aspect
@Order(Ordered.LOWEST_PRECEDENCE - 1)
public class XLockInterceptor {
@Autowired
private RedissonClient redissonClient;
private ExpressionParser parser = new SpelExpressionParser();
private LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
@Around("@annotation(lock.starter.annotation.XLock)")
public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
Object object = null;
MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
Method method = joinPointObject.getMethod();
XLock xlock = method.getAnnotation(XLock.class);
if(null == xlock) {
return pjp.proceed();
}
Object[] args = pjp.getArgs();
String[] params = discoverer.getParameterNames(method);
EvaluationContext context = new StandardEvaluationContext();
for (int i = 0; i < params.length; i++) {
context.setVariable(params[i],args[i]);
}
String keySpel = xlock.key();
Expression keyExpression = parser.parseExpression(keySpel);
String key = keyExpression.getValue(context,String.class);
RLock lock = redissonClient.getLock(key);
long waitTime = xlock.waitTime();
long leaseTime = xlock.leaseTime();
TimeUnit unit = xlock.unit();
try {
if(lock.tryLock(waitTime,leaseTime,unit)) {
object = pjp.proceed();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
//鎖被持有,并且被當前線程持有
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
return object;
}
}切面邏輯使用around攔截模式,解析使用了@XLock注解的方法,然后織入加鎖解鎖邏輯。
5.定義自動注入配置
@Configuration
@ConditionalOnClass({RedissonClient.class, RedissonLock.class})
@EnableConfigurationProperties(RedissonProperties.class)
@Slf4j
public class XLockAutoConfiguration {
private RedissonProperties redissonProperties;
public XLockAutoConfiguration(RedissonProperties redissonProperties) {
this.redissonProperties = redissonProperties;
}
@Bean
@ConditionalOnMissingBean(RedissonClient.class)
public RedissonClient redisson() {
String password = this.redissonProperties.getPassword();
String port = this.redissonProperties.getPort();
int database = this.redissonProperties.getDatabase();
ServerType serverType = ServerType.of(this.redissonProperties.getServerType());
if(null == serverType) {
throw new RuntimeException("server type not support;serverType=" + this.redissonProperties.getServerType());
}
Config config = new Config();
if(ServerType.SINGLE_SERVER.equals(serverType)) {
String address = "redis://" + redissonProperties.getSingleServer().getHost() + ":" + port;
SingleServerConfig singleServerConfig = config.useSingleServer()
.setAddress(address)
.setDatabase(database);
if(null != password) {
singleServerConfig.setPassword(password);
}
} else if(ServerType.CLUSTER_SERVERS.equals(serverType)) {
ClusterServersConfig clusterServersConfig = config.useClusterServers();
String hosts = redissonProperties.getClusterServers().getHosts();
for (String host : hosts.split(",")) {
clusterServersConfig.addNodeAddress("redis://" + host + ":" + port);
}
if(null != password) {
clusterServersConfig.setPassword(password);
}
} else if (ServerType.MASTER_SLAVE_SERVERS.equals(serverType)) {
MasterSlaveServersConfig masterSlaveServersConfig = config.useMasterSlaveServers()
.setDatabase(database);
masterSlaveServersConfig.setMasterAddress("redis://" + redissonProperties.getMasterSlaveServers().getMasterHost() + ":" + port);
for (String slaveHost : redissonProperties.getMasterSlaveServers().getSlaveHosts().split(",")) {
masterSlaveServersConfig.addSlaveAddress("redis://" + slaveHost + ":" + port);
}
if(null != password) {
masterSlaveServersConfig.setPassword(password);
}
} else if (ServerType.REPLICATED_SERVERS.equals(serverType)) {
ReplicatedServersConfig replicatedServersConfig = config.useReplicatedServers()
.setDatabase(database);
for (String host : this.redissonProperties.getReplicatedServers().getHosts().split(",")) {
replicatedServersConfig.addNodeAddress("redis://" + host + ":" + port);
}
if(null != password) {
replicatedServersConfig.setPassword(password);
}
} else if (ServerType.SENTINEL_SERVERS.equals(serverType)) {
SentinelServersConfig sentinelServersConfig = config.useSentinelServers()
.setDatabase(database)
.setMasterName(this.redissonProperties.getSentinelServers().getMasterName());
for (String host : this.redissonProperties.getSentinelServers().getHosts().split(",")) {
sentinelServersConfig.addSentinelAddress("redis://" + host + ":" + port);
}
if(null != password) {
sentinelServersConfig.setPassword(password);
}
}
return Redisson.create(config);
}
@Bean
@ConditionalOnBean(RedissonClient.class)
public XLockInterceptor xLockInterceptor() {
return new XLockInterceptor();
}
}在用戶項目中如果沒有定義或者注入RedissonClient,那么通過starter注入RedissonClient,并且支持singleServer、clusterServers、masterSlave、replicatedServer和sentinelServer等模式。 并通過@Bean方式注入暴露鎖切面。
6.自動配置
在starter工程的META-INF/spring.factories中定義自動配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ lock.starter.config.XLockAutoConfiguration
基于spring的SPI模式在項目啟動時自動加載starter的分布式鎖相關配置,開啟分布式鎖能力。 然后打成jar包到倉庫,業(yè)務項目就可以pom依賴引入,使用分布式鎖相關能力了。
三、使用
業(yè)務項目中使用分布式鎖starter的能力比較簡單,引入依賴并定義相關配置即可。
1.引入分布式鎖starter
<dependency>
<groupId>xxx.xxx</groupId>
<artifactId>xlock-redisson-starter</artifactId>
</dependency>2.添加配置
在項目中添加分布式鎖所需的配置,以singleServer模式為例:
redisson:
redis:
port: 6379
password: xxxxxx
database: 0
serverType: 1 #2,3,4,5
singleServer:
host: 127.0.0.13.使用分布式鎖
在需要加鎖的方法上添加@XLock注解,并填入加鎖相關的屬性即可.
@XLock(key = "mylock + #uid",waitTime = 5,leaseTime = 10,unit = TimeUnit.SECONDS)
public void doSomething(String uid) {
//do some business...
}這樣就實現(xiàn)了redisson分布式鎖的使用。
到此這篇關于基于Redisson實現(xiàn)注解式分布式鎖的示例代碼的文章就介紹到這了,更多相關Redisson分布式鎖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
深入dom4j使用selectSingleNode方法報錯分析
本篇文章是對dom4j使用selectSingleNode方法報錯進行了詳細的分析介紹,需要的朋友參考下2013-05-05
IDEA的Web項目右鍵無法創(chuàng)建Servlet問題解決辦法
這篇文章主要介紹了IDEA的Web項目右鍵無法創(chuàng)建Servlet問題解決辦法的相關資料,在IDEA中新建Servlet時發(fā)現(xiàn)缺失選項,可以通過在pom.xml文件中添加servlet依賴解決,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-10-10
java基于雙向環(huán)形鏈表解決丟手帕問題的方法示例
這篇文章主要介紹了java基于雙向環(huán)形鏈表解決丟手帕問題的方法,簡單描述了丟手帕問題,并結合實例形式給出了Java基于雙向環(huán)形鏈表解決丟手帕問題的步驟與相關操作技巧,需要的朋友可以參考下2017-11-11
java8 forEach結合Lambda表達式遍歷 List操作
這篇文章主要介紹了java8 forEach結合Lambda表達式遍歷 List操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

