1. 概述
本章主要介绍saturn业务层分布式并发锁
1.1. 分布式锁介绍
2. 编码指南
2.1. 依赖引入
pom.xml
<
dependency
>
<
groupId
>com.huifu.saturn</
groupId
>
<
artifactId
>saturn-redis</
artifactId
>
<
version
>${saturn.version}</
version
>
</
dependency
>
|
2.2. 代码实例
src\java\resources\application-biz.xml(单元测试日志输出)
<
bean
id
=
"satrunRedisConfig"
class
=
"com.huifu.saturn.redis.SatrunRedisConfig"
init-method
=
"init"
>
<!--本机方式,直接使用master(127.0.0.1:6379)-->
<
property
name
=
"userSentinel"
value
=
"false"
/>
<!--测试、线上环境sentinel配置(192.168.21.205:28389)-->
<
property
name
=
"userSentinel"
value
=
"true"
/>
<
property
name
=
"hostName"
value
=
"${redis.ipaddr}"
/>
<
property
name
=
"port"
value
=
"${redis.port}"
/>
</
bean
>
<
import
resource
=
"classpath*:applicationContext-lock.xml"
></
import
>
<!--当使用spring的TransactionTemplate处理事务时需要引入-->
<
import
resource
=
"classpath*:applicationContext-lock-aspectj-template.xml"
></
import
>
|
/**
* lockSample.
*/
public
class
LockSampleBiz{
@Autowired
LockFactory lockFactory;
public
SampleBO doSomething() {
RLock lock = lockFactory.getLock(
"proect_xx_lock_1"
);
if
(lock.tryLock(
5
, TimeUnit.SECONDS)){
System.out.println(
"lock"
);
}
else
{
System.out.println(
"lock fial"
);
}
lock.unlock();
}
}
|
/**
* 使用TransactionTemplate处理事务,需要在事务提交后才释放锁,引入aspectj增强后自动释放,调用如下:
*/
public
class
LockTransactionSampleBiz{
@Autowired
LockFactory lockFactory;
@Autowired
private
TransactionTemplate transactionTemplate;
public
void
doSomethingWithTransaction(Object object) {
transactionTemplate.execute(
new
TransactionCallback<Object>() {
@Override
public
Object doInTransaction(TransactionStatus status) {
boolean
exists = isExists(object);
if
(!exists){
RLock lock = lockFactory.getLock(
"proect_xx_lock_2"
);
try
{
if
(lock.tryLock(
5
, TimeUnit.SECONDS)){
if
(isExists(object)){
//doSomething
}
}
else
{
//锁定失败后处理
}
}
catch
(InterruptedException e) {
//handle exception 报警satrun分布式锁服务异常
}
}
}
});
}
}
|
3. 注意事项
注意不要使用嵌套锁,请尽量设计只使用一个锁