贺磊的博客

唯有高屋建瓴,方成水到渠成

Spring Cloud 指定包、类、方法名实现AOP切片登陆记录统计功能

1. 所需 jar 包:

<!--tools-->
<properties>
    <commons.collections4.version>4.1</commons.collections4.version>
    <commons.lang3.version>3.4</commons.lang3.version>
    <dom4j.version>1.6.1</dom4j.version>
</properties>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>${commons.collections4.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>${commons.lang3.version}</version>
</dependency>
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>${dom4j.version}</version>
</dependency>

2. 代码:

package com.dmap.auth.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class LoginHistoryV1Aop {

    //只匹配 api 包中以下 5 个类中的以 ogin 结尾的方法
    @Pointcut("execution(public * com.dmap.auth.controller.api.LoginController.*ogin(..)) " +
            "|| execution(public * com.dmap.auth.controller.api.QQController.*ogin(..)) " +
            "|| execution(public * com.dmap.auth.controller.api.WechatController.*ogin(..)) " +
            "|| execution(public * com.dmap.auth.controller.api.WeboController.*ogin(..)) " +
            "|| execution(public * com.dmap.auth.controller.api.LenovoController.*ogin(..))")
    public void loginHistoryLog() {
        //Do nothing in this method.
    }

    @AfterReturning(pointcut = "loginHistoryLog()", returning = "object")
    public void doAfterReturning(JoinPoint joinPoint, Object object) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        String tempIp = "";
        if (attributes != null) {
            request = attributes.getRequest();
            if (request != null) {
                tempIp = request.getRemoteAddr();
            }
        }
        String ip = tempIp;//获得 ip 地址
        Object value = object; //object 是切片所拦截的方法的返回值
        String classMethod = joinPoint.getSignature().getName();//获得调用的方法名称
    }

}

阅读更多
文章标签: java
个人分类: 程序人生
上一篇封装微软(Microsoft) Azure 获得container 实现增加、查询、删除功能
下一篇Spring cloud 后台 download(下载) Excel, 查询数据上传到微软 Azure 返回下载链接
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭