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、在对应的方法上使用

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

相关推荐
Pniubi几秒前
agent处理封号怎么解决误封问题
开发语言·python
Rain的Java大神之路1 分钟前
Java 三层架构,90% 的人只答对一半:Controller 不是瘦,Service 不是透传,Dao 不是只写 SQL
java·后端·面试
Thomas.Sir3 分钟前
第29课:微服务异步调用、线程池优化 & 事件驱动开发
java·redis·微服务
.Hypocritical.6 分钟前
【Java 进阶】泛型深度解析|泛型类、泛型方法、通配符、类型擦除、PECS 原则
java·开发语言·泛型
VX_bysjlw9857 分钟前
基于PHP的论坛系统设计与实现 35136-计算机毕设原创(免费领源码+带部署教程)
开发语言·php·apache·laravel·thinkphp·phpstudy·wampserver
忆~遂愿9 分钟前
电影照片散在硬盘里不好找?我用群晖+Plex整理成可远程访问的家庭媒体库
开发语言·php
这个DBA有点耶12 分钟前
MySQL B-tree索引并发控制优化:写密集场景的锁瓶颈与内核级解法
java·数据库·程序人生·算法·database·dba
RuoyiOffice32 分钟前
Spring AI+Vue3 企业知识库设计:让每个答案有依据,让每份资料守住权限
java·spring boot·vue3·rag·企业知识库·spring ai·ruoyi office
卢锡荣1 小时前
乐得瑞Type-c接口产品描述
c语言·开发语言
晴天的雨.9921 小时前
【C++】模板进阶
开发语言·c++·算法