java spring boot 自定义 aop

以一个锁的加锁和释放为例

1、先定义注解

java 复制代码
/**
 * 锁切面
 * @author fmj
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface VersionLockAOP {
}

2、然后定义切面类以及切点

java 复制代码
/**
 * 切面
 */
@Component
@Aspect
@Slf4j
public class VersionLockAOPAspect {
    /**
     * 之前
     * @param joinPoint
     */
    @Before(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
    public void VersionLockAOPBeforePoint(JoinPoint joinPoint) {
        try {
            switch (joinPoint.getSignature().getName()) {
                case "saveVersion":
                    if (!SingleUtil.SINGLE.getReentrantLockSaveVersion().tryLock(2000L, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("saveVersion获取锁失败");
                    }
                    return;
                case "saveVersionHistory":
                    if (!SingleUtil.SINGLE.getReentrantLockSaveUpgrade().tryLock(2000L, TimeUnit.MILLISECONDS)) {
                        throw new RuntimeException("saveVersionHistory获取锁失败");
                    }
                    return;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("获取锁:" + e.getMessage());
        }
    }

    /**
     * 之后
     * @param joinPoint
     */
    @After(value = "@annotation(com.gscloud.modules.pos.upgrade.aop.VersionLockAOP)")
    public void VersionLockAOPAfterPoint(JoinPoint joinPoint) {
        switch (joinPoint.getSignature().getName()) {
            case "saveVersion":
                if (SingleUtil.SINGLE.getReentrantLockSaveVersion().isLocked()) {
                    SingleUtil.SINGLE.getReentrantLockSaveVersion().unlock();
                }
                return;
            case "saveVersionHistory":
                if(SingleUtil.SINGLE.getReentrantLockSaveUpgrade().isLocked()){
                    SingleUtil.SINGLE.getReentrantLockSaveUpgrade().unlock();
                }
                return;
        }
    }
}

3、在对应的方法上使用

执行该方法前后都会进入切点方法执行对应逻辑

相关推荐
脾气有点小暴1 分钟前
JavaScript 数据存储方法全解析:从基础到进阶
开发语言·javascript·ecmascript
步步为营DotNet4 分钟前
深入理解IAsyncEnumerable:异步迭代的底层实现与应用优化
java·服务器·数据库
繁华似锦respect4 分钟前
C++ 内存分配器-allocator
开发语言·c++·设计模式
沐知全栈开发6 分钟前
Swift 基本语法
开发语言
CoderYanger6 分钟前
动态规划算法-子数组、子串系列(数组中连续的一段):21.乘积最大子数组
开发语言·算法·leetcode·职场和发展·动态规划·1024程序员节
qq_479875437 分钟前
protobuf[1]
java·开发语言
装不满的克莱因瓶9 分钟前
【Java架构 搭建环境篇三】Linux安装Git详细教程
java·linux·运维·服务器·git·架构·centos
运维@小兵12 分钟前
使用Spring-ai实现同步响应和流式响应
java·人工智能·spring-ai·ai流式响应
CoderYanger13 分钟前
A.每日一题——3432. 统计元素和差值为偶数的分区方案
java·数据结构·算法·leetcode·1024程序员节
Geoking.14 分钟前
JDK 版本与 Java 版本的关系
java·开发语言