ARTICLE · 1392058
拒绝模板代码!@Lock解决并发问题
拒绝模板代码!@Lock解决并发问题《Spring Boot 3实战案例锦集》PDF电子书已更新至130篇! 🎉🎉《Spring Boot实战案例合集》目前已更新236个案例,我们将持续不断的更新。文末有电子书目录。→ 现在就订阅合集
2.实战案例 2.1 定义注解&接口 定义Lock接口 JVM级锁实现 Redis分布式锁实现 锁配置 2.2 切面定义 定义BeanPostprocessor 2.3 测试 不加锁测试 
测试用例 执行结果 
修改Service方法添加@Lock注解 执行结果 
以上是本篇文章的全部内容,如对你有帮助帮忙点赞+转发+收藏 无需额外服务!用DJL在Java中直接跑本地大模型
环境:Spring Boot 3.5.0
1. 简介
在实际业务开发中,并发问题一直是绕不开的话题。当多个请求同时修改同一份数据时,如果没有合理的控制机制,很容易出现数据覆盖、状态错乱等问题。
很多开发者第一时间会想到手写锁,通过 synchronized、Lock 等方式解决,但随着业务复杂度提升,大量重复的锁代码不仅难维护,也容易埋下新的问题。如下示例代码:
RLock lock = redisson.getLock("myLock");// 1. 方式1// 传统锁定方法lock.lock();// 或者获取锁,并在10秒后自动解锁// 2. 方式2// lock.lock(10, TimeUnit.SECONDS);// 3. 方式3// 或者等待获取锁最多100秒,并在10秒后自动解锁boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);if (res) {try {// 业务代码} finally {lock.unlock();}}
本篇文章,我们将通过自定义 @Lock 更直接的并发控制方式(不用再写如上的模版代码),通过声明式配置处理资源竞争问题。
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Lock {String key() ;}
public interface PackLock extends Lock {@Overridedefault void lockInterruptibly() throws InterruptedException {}@Overridedefault boolean tryLock() {return false;}@Overridedefault boolean tryLock(long time, TimeUnit unit) throws InterruptedException {return false;}@Overridedefault Condition newCondition() {return null;}}
public class ReentrantPackLock implements PackLock {private final ReentrantLock lock;private final LockProperties lockProperties ;publicReentrantPackLock(LockProperties lockProperties) {this.lock = new ReentrantLock();this.lockProperties = lockProperties ;}@Overridepublicvoidlock() {lock.lock();}@OverridepublicvoidlockInterruptibly() throws InterruptedException {lock.lockInterruptibly();}@Overridepublic boolean tryLock() {try {return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit());} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new RuntimeException(e) ;}}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException {return lock.tryLock(time, unit);}@Overridepublicvoidunlock() {lock.unlock();}@Overridepublic Condition newCondition() {return lock.newCondition();}}
public class RedissonPackLock implements PackLock {private final RLock lock;private final LockProperties lockProperties;publicRedissonPackLock(RedissonClient redissonClient, LockProperties lockProperties, Lock annotation) {this.lockProperties = lockProperties ;this.lock = redissonClient.getLock(annotation.key()) ;}@Overridepublicvoidlock() {lock.lock();}@OverridepublicvoidlockInterruptibly() throws InterruptedException {lock.lockInterruptibly();}@Overridepublic boolean tryLock() {try {return lock.tryLock(this.lockProperties.time(), this.lockProperties.unit());} catch (InterruptedException e) {Thread.currentThread().interrupt();throw new RuntimeException(e) ;}}@Overridepublic boolean tryLock(long time, TimeUnit unit) throws InterruptedException {return lock.tryLock(time, unit);}@Overridepublicvoidunlock() {lock.unlock();}@Overridepublic Condition newCondition() {throw new UnsupportedOperationException("Redisson distributed lock does not support Condition") ;}}
@ConfigurationProperties(prefix = "pack.lock")public record LockProperties(@DefaultValue("LOCAL") LockType type, String prefix, @DefaultValue("-1") Long time, @DefaultValue("") TimeUnit unit) {public enum LockType {LOCAL, REDIS}}
public class LockAdvisor implements PointcutAdvisor {private final Map<String, PackLock> localLockCache = new ConcurrentHashMap<>();private final LockProperties lockProperties ;private final RedissonClient redissonClient ;public LockAdvisor(LockProperties lockProperties, RedissonClient redissonClient) {this.lockProperties = lockProperties;this.redissonClient = redissonClient;}@Overridepublic Advice getAdvice() {return new LockInterceptor(this.lockProperties, this.redissonClient) ;}@Overridepublic Pointcut getPointcut() {return new StaticMethodMatcherPointcut() {@Overridepublic boolean matches(Method method, Class<?> targetClass) {return method.isAnnotationPresent(Lock.class) ;}} ;}public class LockInterceptor implements MethodInterceptor {private final LockProperties lockProperties ;private final RedissonClient redissonClient ;public LockInterceptor(LockProperties lockProperties, RedissonClient redissonClient) {this.lockProperties = lockProperties;this.redissonClient = redissonClient;}@Overridepublic Object invoke(MethodInvocation invocation) throws Throwable {Lock annotation = invocation.getMethod().getAnnotation(Lock.class) ;if (annotation == null) {return invocation.proceed() ;}LockType type = this.lockProperties.type() ;PackLock packLock = null ;if (type == LockType.LOCAL) {packLock = localLockCache.computeIfAbsent(annotation.key(), k -> new ReentrantPackLock(lockProperties));} else {packLock = new RedissonPackLock(redissonClient, lockProperties, annotation) ;}packLock.lock() ;try {return invocation.proceed() ;} finally {packLock.unlock() ;}}}}
public class LockProxyCreator implements BeanPostProcessor, Ordered {private final LockAdvisor lockAdvisor ;public LockProxyCreator(LockProperties lockProperties, RedissonClient redissonClient) {this.lockAdvisor = new LockAdvisor(lockProperties, redissonClient) ;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean) ;boolean needCreator = false ;Method[] methods = targetClass.getDeclaredMethods() ;for (Method method : methods) {if (Modifier.isPublic(method.getModifiers()) &&method.isAnnotationPresent(Lock.class)) {needCreator = true ;break ;}}if (!needCreator) {return bean ;}if (AopUtils.isAopProxy(bean)) {Advised advised = (Advised) bean ;advised.addAdvisor(0, this.lockAdvisor);return bean ;}ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(bean);proxyFactory.setExposeProxy(true);proxyFactory.setProxyTargetClass(true) ;proxyFactory.addAdvisor(this.lockAdvisor);return proxyFactory.getProxy();}@Overridepublic int getOrder() {return Ordered.LOWEST_PRECEDENCE ;}}
@Transactionalpublic void deduct(Long stockId, Integer deductNum) {this.stockRepository.findById(stockId).ifPresent(stock -> {if (stock.getAmount() >= deductNum) {int ret = stockRepository.deductStock(stockId, deductNum);System.err.println("%s - %s".formatted(Thread.currentThread().getName(), ret > 0 ? "成功购买" : "库存不足")) ;}}) ;}

@Testpublic void testDeduct() throws Exception {final int COUNT = 30 ;Thread[] threads = new Thread[COUNT] ;CountDownLatch cdl = new CountDownLatch(COUNT) ;CyclicBarrier cb = new CyclicBarrier(COUNT) ;for (int i = 0; i < COUNT; i++) {threads[i] = new Thread(() -> {try {cb.await() ;} catch (Exception e) {}stockService.deduct(1L, 10) ;cdl.countDown() ;}) ;}for (int i = 0; i < COUNT; i++) {threads[i].start();}cdl.await();}

@Transactional@Lock(key = "sss")public void deduct(Long stockId, Integer deductNum)

优雅!Chain 结合 Spring Boot 轻松实现强大的责任链模式
优雅!基于Spring Boot字段加密后的模糊查询,支持MyBatis, JPA















































































