• Spring Boot AOP记录用户操作日志


    在Spring框架中,使用AOP配合自定义注解可以方便的实现用户操作的监控。首先搭建一个基本的Spring Boot Web环境开启Spring Boot,然后

    引入必要依赖:

     <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
    
            <!-- aop依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-aop</artifactId>
            </dependency>
    
            <!-- mysql驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.41</version>
            </dependency>
    
            <!-- druid数据源驱动 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.10</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>

    自定义注解

    定义一个方法级别的@Log注解,用于标注需要监控的方法:

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Log {
        String value() default "";
    }

    创建库表和实体

    在数据库中创建一张sys_log表,用于保存用户的操作日志

     实体:

    public class SysLog implements Serializable {
    
        private Integer id;
        private String username;
        private String operation;
        private Integer time;
        private String method;
        private String params;
        private String ip;
        private Date createTime;
    
    ............

    dao:

    public interface SysLogDao {
        void saveSysLog(SysLog syslog);
    }
    @Repository
    public class SysLogDaoImpl implements SysLogDao {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        @Override
        public void saveSysLog(SysLog syslog) {
    
            System.out.println(syslog);
    
            StringBuffer sql = new StringBuffer("insert into sys_log ");
            sql.append("(id,username,operation,time,method,params,ip,create_time) ");
            sql.append("values(NULL,?,?,?,?,?,?,?)");
            String sql2=sql.toString();
            jdbcTemplate.update(sql2,syslog.getUsername(),syslog.getOperation(),syslog.getTime(),syslog.getMethod(),syslog.getParams(),syslog.getIp(),syslog.getCreateTime());
            jdbcTemplate.update(sql2);
    
        }
    }

    Aspect:

    @Aspect
    @Component
    public class LogAspect {
    
        @Autowired
        private SysLogDao sysLogDao;
    
        @Pointcut("@annotation(com.lc.aop.annotation.Log)")
        public void pointcut() { }
    
        @Around("pointcut()")
        public Object around(ProceedingJoinPoint point) {
            Object result = null;
            long beginTime = System.currentTimeMillis();
            try {
                // 执行方法
                result = point.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
            }
            // 执行时长(毫秒)
            long time = System.currentTimeMillis() - beginTime;
            // 保存日志
            saveLog(point, time);
            return result;
        }
    
        private void saveLog(ProceedingJoinPoint joinPoint, long time) {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            SysLog sysLog = new SysLog();
            Log logAnnotation = method.getAnnotation(Log.class);
            if (logAnnotation != null) {
                // 注解上的描述
                sysLog.setOperation(logAnnotation.value());
            }
            // 请求的方法名
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = signature.getName();
            sysLog.setMethod(className + "." + methodName + "()");
            // 请求的方法参数值
            Object[] args = joinPoint.getArgs();
            // 请求的方法参数名称
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paramNames = u.getParameterNames(method);
            if (args != null && paramNames != null) {
                String params = "";
                for (int i = 0; i < args.length; i++) {
                    params += "  " + paramNames[i] + ": " + args[i];
                }
                sysLog.setParams(params);
            }
            // 获取request
            HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
            // 设置IP地址
            sysLog.setIp(IPUtils.getIpAddr(request));
            // 模拟一个用户名
            sysLog.setUsername("mrbird");
            sysLog.setTime((int) time);
            sysLog.setCreateTime(new Date());
            // 保存系统日志
            sysLogDao.saveSysLog(sysLog);
        }
    }

    controller:

    @RestController
    public class TestController {
    
        @Log("执行方法一")
        @GetMapping("/one")
        public void methodOne(String name) { }
    
        @Log("执行方法二")
        @GetMapping("/two")
        public void methodTwo() throws InterruptedException {
            Thread.sleep(2000);
        }
    
        @Log("执行方法三")
        @GetMapping("/three")
        public void methodThree(String name, String age) { }
    }

    工具类:

    public class IPUtils {
        /**
         * 获取IP地址
         *
         * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
         * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
         */
        public static String getIpAddr(HttpServletRequest request) {
    
            String ip = request.getHeader("x-forwarded-for");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
        }
    }
    public class HttpContextUtils {
        public static HttpServletRequest getHttpServletRequest() {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
    }

    application.properties

    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/springboot
    spring.datasource.username=root
    spring.datasource.password=123456

    项目结构:

    访问后:

  • 相关阅读:
    Vim自动补全神器YouCompleteMe的配置
    sudo apt-get update 时出现的hit、ign、get的含义
    C语言可变参数宏及‘##’在可变参数中的作用
    搬书游戏
    程序中数字取反结果公式
    利用宏定义中的##实现函数模板的作用
    C中的空宏定义,即只有一个参数
    浏览器缓存技术介绍
    Vue相关原理以及手写一个MyVue
    详解JS中的prototype、__proto__与constructor(图解)
  • 原文地址:https://www.cnblogs.com/crazy-lc/p/12449022.html
Copyright © 2020-2023  润新知