Spring boot 添加 AOP【打印访问日志,处理重复提交】

@Aspect
@Component
@Slf4j
public class ControllerConfig {

    @Autowired
    private RedissonService redissonService;

    @Pointcut(value = "execution(public * com.*.controller.*.*(..) )")
    private void point() {
    }

    @Around("point()")
    public Object pointcut(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        String methodName = proceedingJoinPoint.getSignature().getName();
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //参数列表
        Object[] args = proceedingJoinPoint.getArgs();

        StringBuilder sb = new StringBuilder();
        Arrays.asList(args).forEach((o) -> {
            if (!(o instanceof ServletRequest) && !(o instanceof MultipartFile) && !(o instanceof ServletResponse)) {
                sb.append(JSON.toJSONString(o) + ",");
            }
        });

        //获取参数名
        String[] argNames = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterNames();

        String userId = null;
        for (int i = 0; i < argNames.length; i++) {
            if ("userId".equals(argNames[i])) {
                userId = String.valueOf(args[i]);
            }
        }

        log.info("执行->[{}]类的->[{}]方法的请求参数为:->[{}]", className, methodName, sb.toString());

        Object proceed = null;
        //处理重复提交
        if (userId != null) {   
            String key = new StringBuilder("redisLock").append(className).append("-").append(methodName).append("-").append(userId).toString();
            RLock lock = redissonService.getRLock(key);
            if(lock.isLocked()){
                return R.error("系统繁忙,请稍后");
            }
            try {
                lock.lock();
                proceed = proceedingJoinPoint.proceed();
            } catch (Exception e) {
                log.error("系统异常,异常信息:{}", e);
                proceed = R.error();
            } finally {
                lock.unlock();
            }

        } else {
            proceed = proceedingJoinPoint.proceed();
        }

        long endTime = System.currentTimeMillis();
        log.info("执行->[{}]类的[{}]方法的返回报文为:->[{}],执行时长为:[{}] ms", className, methodName, JSON.toJSONString(proceed), (endTime - startTime));
        return proceed;
    }
}
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.5.7</version>
</dependency>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值