boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
…
lock.unlock();
Redisson同时还为分布式锁提供了异步执行的相关方法:
RLock lock = redisson.getLock(“anyLock”);
lock.lockAsync();
lock.lockAsync(10, TimeUnit.SECONDS);
Future res = lock.tryLockAsync(100, 10, TimeUnit.SECONDS);
公平锁
Redisson分布式可重入公平锁也是实现了java.util.concurrent.locks.Lock接口的一种RLock对象。在提供了自动过期解锁功能的同时,保证了当多个Redisson客户端线程同时请求加锁时,优先分配给先发出请求的线程。
RLock fairLock = redisson.getFairLock(“anyLock”);
// 最常见的使用方法
fairLock.lock();
// 支持过期解锁功能
// 10秒钟以后自动解锁
// 无需调用unlock方法手动解锁
fairLock.lock(10, TimeUnit.SECONDS);
// 尝试加锁,最多等待100秒,上锁以后10秒自动解锁
boolean res = fairLock.tryLock(100, 10, TimeUnit.SECONDS);
…
fairLock.unlock();
其他锁
Redisson还提供了其他机制的锁,如联锁(MultiLock)、红锁(RedLock)等。详细可参考:分布式锁和同步器
使用Redisson实现分布式锁
定义回调接口
/**
- 分布式锁回调接口
*/
public interface DistributedLockCallback {
/**
-
调用者必须在此方法中实现需要加分布式锁的业务逻辑
-
@return
*/
public T process();
/**
-
得到分布式锁名称
-
@return
*/
public String getLockName();
}
定义分布式锁模板
/**
- 分布式锁操作模板
*/
public interface DistributedLockTemplate {
long DEFAULT_WAIT_TIME = 30;
long DEFAULT_TIMEOUT = 5;
TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;
/**
-
使用分布式锁,使用锁默认超时时间。
-
@param callback
-
@param fairLock 是否使用公平锁
-
@return
*/
T lock(DistributedLockCallback callback, boolean fairLock);
/**
-
使用分布式锁。自定义锁的超时时间
-
@param callback
-
@param leaseTime 锁超时时间。超时后自动释放锁。
-
@param timeUnit
-
@param fairLock 是否使用公平锁
-
@param
-
@return
*/
T lock(DistributedLockCallback callback, long leaseTime, TimeUnit timeUnit, boolean fairLock);
/**
-
尝试分布式锁,使用锁默认等待时间、超时时间。
-
@param callback
-
@param fairLock 是否使用公平锁
-
@param
-
@return
*/
T tryLock(DistributedLockCallback callback, boolean fairLock);
/**
-
尝试分布式锁,自定义等待时间、超时时间。
-
@param callback
-
@param waitTime 获取锁最长等待时间
-
@param leaseTime 锁超时时间。超时后自动释放锁。
-
@param timeUnit
-
@param fairLock 是否使用公平锁
-
@param
-
@return
*/
T tryLock(DistributedLockCallback callback, long waitTime, long leaseTime, TimeUnit timeUnit, boolean fairLock);
}
实现分布式锁模板
public class SingleDistributedLockTemplate implements DistributedLockTemplate {
private RedissonClient redisson;
public SingleDistributedLockTemplate() {
}
public SingleDistributedLockTemplate(RedissonClient redisson) {
this.redisson = redisson;
}
@Override
public T lock(DistributedLockCallback callback, boolean fairLock) {
return lock(callback, DEFAULT_TIMEOUT, DEFAULT_TIME_UNIT, fairLock);
}
@Override
public T lock(DistributedLockCallback callback, long leaseTime, TimeUnit timeUnit, boolean fairLock) {
RLock lock = getLock(callback.getLockName(), fairLock);
try {
lock.lock(leaseTime, timeUnit);
return callback.process();
} finally {
if (lock != null && lock.isLocked()) {
lock.unlock();
}
}
}
@Override
public T tryLock(DistributedLockCallback callback, boolean fairLock) {
return tryLock(callback, DEFAULT_WAIT_TIME, DEFAULT_TIMEOUT, DEFAULT_TIME_UNIT, fairLock);
}
@Override
public T tryLock(DistributedLockCallback callback, long waitTime, long leaseTime, TimeUnit timeUnit, boolean fairLock) {
RLock lock = getLock(callback.getLockName(), fairLock);
try {
if (lock.tryLock(waitTime, leaseTime, timeUnit)) {
return callback.process();
}
} catch (InterruptedException e) {
} finally {
if (lock != null && lock.isLocked()) {
lock.unlock();
}
}
return null;
}
private RLock getLock(String lockName, boolean fairLock) {
RLock lock;
if (fairLock) {
lock = redisson.getFairLock(lockName);
} else {
lock = redisson.getLock(lockName);
}
return lock;
}
public void setRedisson(RedissonClient redisson) {
this.redisson = redisson;
}
}
使用SingleDistributedLockTemplate
DistributedLockTemplate lockTemplate = …;
final String lockName = …;
lockTemplate.lock(new DistributedLockCallback() {
@Override
public Object process() {
//do some business
return null;
}
@Override
public String getLockName() {
return lockName;
}
}, false);
但是每次使用分布式锁都要写类似上面的重复代码,有没有什么方法可以只关注核心业务逻辑代码的编写,即上面的"do some business"。下面介绍如何使用Spring AOP来实现这一目标。
使用Spring AOP简化分布式锁
定义注解@DistributedLock
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DistributedLock {
/**
-
锁的名称。
-
如果lockName可以确定,直接设置该属性。
*/
String lockName() default “”;
/**
- lockName后缀
*/
String lockNamePre() default “”;
/**
- lockName后缀
*/
String lockNamePost() default “lock”;
/**
-
获得锁名时拼接前后缀用到的分隔符
-
@return
*/
String separator() default “.”;
/**
-
获取注解的方法参数列表的某个参数对象的某个属性值来作为lockName。因为有时候lockName是不固定的。
-
当param不为空时,可以通过argNum参数来设置具体是参数列表的第几个参数,不设置则默认取第一个。
*/
String param() default “”;
/**
- 将方法第argNum个参数作为锁
*/
int argNum() default 0;
/**
-
是否使用公平锁。
-
公平锁即先来先得。
*/
boolean fairLock() default false;
/**
- 是否使用尝试锁。
*/
boolean tryLock() default false;
/**
-
最长等待时间。
-
该字段只有当tryLock()返回true才有效。
*/
long waitTime() default 30L;
/**
-
锁超时时间。
-
超时时间过后,锁自动释放。
-
建议:
-
尽量缩简需要加锁的逻辑。
*/
long leaseTime() default 5L;
/**
- 时间单位。默认为秒。
*/
TimeUnit timeUnit() default TimeUnit.SECONDS;
}
定义切面代码
@Aspect
@Component
public class DistributedLockAspect {
@Autowired
private DistributedLockTemplate lockTemplate;
@Pointcut(“@annotation(cn.sprinkle.study.distributedlock.common.annotation.DistributedLock)”)
public void DistributedLockAspect() {}
@Around(value = “DistributedLockAspect()”)
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
//切点所在的类
Class targetClass = pjp.getTarget().getClass();
//使用了注解的方法
String methodName = pjp.getSignature().getName();
Class[] parameterTypes = ((MethodSignature)pjp.getSignature()).getMethod().getParameterTypes();
Method method = targetClass.getMethod(methodName, parameterTypes);
Object[] arguments = pjp.getArgs();
final String lockName = getLockName(method, arguments);
return lock(pjp, method, lockName);
}
@AfterThrowing(value = “DistributedLockAspect()”, throwing=“ex”)
public void afterThrowing(Throwable ex) {
throw new RuntimeException(ex);
}
public String getLockName(Method method, Object[] args) {
Objects.requireNonNull(method);
DistributedLock annotation = method.getAnnotation(DistributedLock.class);
String lockName = annotation.lockName(),
param = annotation.param();
if (isEmpty(lockName)) {
if (args.length > 0) {
if (isNotEmpty(param)) {
Object arg;
if (annotation.argNum() > 0) {
arg = args[annotation.argNum() - 1];
} else {
arg = args[0];
}
lockName = String.valueOf(getParam(arg, param));
} else if (annotation.argNum() > 0) {
lockName = args[annotation.argNum() - 1].toString();
}
}
}
if (isNotEmpty(lockName)) {
String preLockName = annotation.lockNamePre(),
postLockName = annotation.lockNamePost(),
separator = annotation.separator();
StringBuilder lName = new StringBuilder();
if (isNotEmpty(preLockName)) {
lName.append(preLockName).append(separator);
}
lName.append(lockName);
if (isNotEmpty(postLockName)) {
lName.append(separator).append(postLockName);
}
lockName = lName.toString();
return lockName;
}
throw new IllegalArgumentException(“Can’t get or generate lockName accurately!”);
}
/**
-
从方法参数获取数据
-
@param param
-
@param arg 方法的参数数组
-
@return
*/
public Object getParam(Object arg, String param) {
if (isNotEmpty(param) && arg != null) {
try {
Object result = PropertyUtils.getProperty(arg, param);
return result;
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(arg + “没有属性” + param + “或未实现get方法。”, e);
} catch (Exception e) {
throw new RuntimeException(“”, e);
}
}
return null;
}
public Object lock(ProceedingJoinPoint pjp, Method method, final String lockName) {
DistributedLock annotation = method.getAnnotation(DistributedLock.class);
boolean fairLock = annotation.fairLock();
boolean tryLock = annotation.tryLock();
if (tryLock) {
return tryLock(pjp, annotation, lockName, fairLock);
} else {
return lock(pjp,lockName, fairLock);
}
}
public Object lock(ProceedingJoinPoint pjp, final String lockName, boolean fairLock) {
return lockTemplate.lock(new DistributedLockCallback() {
@Override
public Object process() {
return proceed(pjp);
}
@Override
public String getLockName() {
return lockName;
}
}, fairLock);
}
public Object tryLock(ProceedingJoinPoint pjp, DistributedLock annotation, final String lockName, boolean fairLock) {
long waitTime = annotation.waitTime(),
leaseTime = annotation.leaseTime();
TimeUnit timeUnit = annotation.timeUnit();
return lockTemplate.tryLock(new DistributedLockCallback() {
@Override
public Object process() {
return proceed(pjp);
}
@Override
public String getLockName() {
return lockName;
}
}, waitTime, leaseTime, timeUnit, fairLock);
}
public Object proceed(ProceedingJoinPoint pjp) {
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
private boolean isEmpty(Object str) {
return str == null || “”.equals(str);
}
private boolean isNotEmpty(Object str) {
return !isEmpty(str);
}
}
使用注解@DistributedLock实现分布式锁
有了上面两段代码,以后需要用到分布式锁,只需在核心业务逻辑方法添加注解@DistributedLock,并设置LockName、fairLock等即可。下面的DistributionService演示了多种使用情景。
@Service
public class DistributionService {
@Autowired
private RedissonClient redissonClient;
@DistributedLock(param = “id”, lockNamePost = “.lock”)
public Integer aspect(Person person) {
RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);
Integer count = map.get(“count”);
if (count > 0) {
count = count - 1;
map.put(“count”, count);
}
return count;
}
@DistributedLock(argNum = 1, lockNamePost = “.lock”)
public Integer aspect(String i) {
RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);
Integer count = map.get(“count”);
if (count > 0) {
count = count - 1;
map.put(“count”, count);
}
return count;
}
@DistributedLock(lockName = “lock”, lockNamePost = “.lock”)
public int aspect(Action action) {
return action.action();
}
}
测试
定义一个Worker类:
public class Worker implements Runnable {
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
private final DistributionService service;
private RedissonClient redissonClient;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal, DistributionService service, RedissonClient redissonClient) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
this.service = service;
this.redissonClient = redissonClient;
}
@Override
public void run() {
try {
startSignal.await();
System.out.println(Thread.currentThread().getName() + " start");
// Integer count = service.aspect(new Person(1, “张三”));
// Integer count = service.aspect(“1”);
Integer count = service.aspect(() -> {
RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);
Integer count1 = map.get(“count”);
if (count1 > 0) {
count1 = count1 - 1;
map.put(“count”, count1);
}
return count1;
});
System.out.println(Thread.currentThread().getName() + ": count = " + count);
doneSignal.countDown();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
定义Controller类:
@RestController
@RequestMapping(“/distributedLockTest”)
public class DistributedLockTestController {
private int count = 10;
@Autowired
private RedissonClient redissonClient;
@Autowired
private DistributionService service;
@RequestMapping(method = RequestMethod.GET)
public String distributedLockTest() throws Exception {
RMap<String, Integer> map = redissonClient.getMap(“distributionTest”);
map.put(“count”, 8);
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(count);
for (int i = 0; i < count; ++i) { // create and start threads
new Thread(new Worker(startSignal, doneSignal, service)).start();
}
startSignal.countDown(); // let all threads proceed
doneSignal.await();
System.out.println(“All processors done. Shutdown connection”);
return “finish”;
}
}
Redisson基本配置:
singleServerConfig:
idleConnectionTimeout: 10000
pingTimeout: 1000
connectTimeout: 10000
timeout: 3000
retryAttempts: 3
retryInterval: 1500
reconnectionTimeout: 3000
failedAttempts: 3
password:
subscriptionsPerConnection: 5
clientName: null
address: “redis://127.0.0.1:6379”
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 10
connectionPoolSize: 64
database: 0
dnsMonitoring: false
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
useLinuxNativeEpoll: false
工程中需要注入的对象:
@Value(“classpath:/redisson-conf.yml”)
Resource configFile;
@Bean(destroyMethod = “shutdown”)
RedissonClient redisson()
throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
总结
阿里伤透我心,疯狂复习刷题,终于喜提offer 哈哈~好啦,不闲扯了
1、JAVA面试核心知识整理(PDF):包含JVM,JAVA集合,JAVA多线程并发,JAVA基础,Spring原理,微服务,Netty与RPC,网络,日志,Zookeeper,Kafka,RabbitMQ,Hbase,MongoDB,Cassandra,设计模式,负载均衡,数据库,一致性哈希,JAVA算法,数据结构,加密算法,分布式缓存,Hadoop,Spark,Storm,YARN,机器学习,云计算共30个章节。
2、Redis学习笔记及学习思维脑图
3、数据面试必备20题+数据库性能优化的21个最佳实践
tionsPerConnection: 5
clientName: null
address: “redis://127.0.0.1:6379”
subscriptionConnectionMinimumIdleSize: 1
subscriptionConnectionPoolSize: 50
connectionMinimumIdleSize: 10
connectionPoolSize: 64
database: 0
dnsMonitoring: false
dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}
useLinuxNativeEpoll: false
工程中需要注入的对象:
@Value(“classpath:/redisson-conf.yml”)
Resource configFile;
@Bean(destroyMethod = “shutdown”)
RedissonClient redisson()
throws IOException {
Config config = Config.fromYAML(configFile.getInputStream());
return Redisson.create(config);
总结
阿里伤透我心,疯狂复习刷题,终于喜提offer 哈哈~好啦,不闲扯了
[外链图片转存中…(img-EZ5CSTjj-1718714812001)]
1、JAVA面试核心知识整理(PDF):包含JVM,JAVA集合,JAVA多线程并发,JAVA基础,Spring原理,微服务,Netty与RPC,网络,日志,Zookeeper,Kafka,RabbitMQ,Hbase,MongoDB,Cassandra,设计模式,负载均衡,数据库,一致性哈希,JAVA算法,数据结构,加密算法,分布式缓存,Hadoop,Spark,Storm,YARN,机器学习,云计算共30个章节。
[外链图片转存中…(img-0sfxTjAb-1718714812002)]
2、Redis学习笔记及学习思维脑图
[外链图片转存中…(img-Lv2esQZ5-1718714812002)]
3、数据面试必备20题+数据库性能优化的21个最佳实践
[外链图片转存中…(img-fSQhpFKN-1718714812002)]