欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring?Boot+Aop記錄用戶操作日志實(shí)戰(zhàn)記錄

 更新時間:2023年04月17日 10:33:41   作者:MAllk33  
在Spring框架中使用AOP配合自定義注解可以方便的實(shí)現(xiàn)用戶操作的監(jiān)控,下面這篇文章主要給大家介紹了關(guān)于Spring?Boot+Aop記錄用戶操作日志實(shí)戰(zhàn)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、前言

本文主要介紹通過Aop記錄用戶操作日志,這也是目前比較常用的用法,由于水平有限,所以可能存在錯漏之處,望指正。

二、實(shí)戰(zhàn)

1、設(shè)計用戶操作日志表: sys_oper_log

用戶操作日志表

對應(yīng)實(shí)體類為SysOperLog.java

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;

/**
 * <p>
 * 操作日志記錄
 * </p>
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysOperLog implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    @ApiModelProperty("主鍵Id")
    private Integer id;

    @ApiModelProperty("模塊標(biāo)題")
    private String title;

    @ApiModelProperty("參數(shù)")
    private String optParam;

    @ApiModelProperty("業(yè)務(wù)類型(0其它 1新增 2修改 3刪除)")
    private Integer businessType;

    @ApiModelProperty("路徑名稱")
    private String uri;

    @ApiModelProperty("操作狀態(tài)(0正常 1異常)")
    private Integer status;

    @ApiModelProperty("錯誤消息")
    private String errorMsg;

    @ApiModelProperty("操作時間")
    private Date operTime;
}

2、引入依賴

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>2.0.9</version>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

3、自定義用戶操作日志注解

MyLog.java

import java.lang.annotation.*;

@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyLog {
    // 自定義模塊名,eg:登錄
    String title() default "";
    // 方法傳入的參數(shù)
    String optParam() default "";
    // 操作類型,eg:INSERT, UPDATE...
    BusinessType businessType() default BusinessType.OTHER;  
}

BusinessType.java — 操作類型枚舉類

public enum BusinessType {
    // 其它
    OTHER,
    // 查找
    SELECT,
    // 新增
    INSERT,
    // 修改
    UPDATE,
    // 刪除
    DELETE,
}

4、自定義用戶操作日志切面

LogAspect.java

import com.alibaba.fastjson.JSONObject;
import iot.sixiang.license.entity.SysOperLog;
import iot.sixiang.license.handler.IotLicenseException;
import iot.sixiang.license.jwt.UserUtils;
import iot.sixiang.license.service.SysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class LogAspect {
    /**
     * 該Service及其實(shí)現(xiàn)類相關(guān)代碼請自行實(shí)現(xiàn),只是一個簡單的插入數(shù)據(jù)庫操作
     */
    @Autowired
    private SysOperLogService sysOperLogService;
    
	/**
     * @annotation(MyLog類的路徑) 在idea中,右鍵自定義的MyLog類-> 點(diǎn)擊Copy Reference
     */
    @Pointcut("@annotation(xxx.xxx.xxx.MyLog)")
    public void logPointCut() {
        log.info("------>配置織入點(diǎn)");
    }

    /**
     * 處理完請求后執(zhí)行
     *
     * @param joinPoint 切點(diǎn)
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 攔截異常操作
     *
     * @param joinPoint 切點(diǎn)
     * @param e         異常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e) {

        // 獲得MyLog注解
        MyLog controllerLog = getAnnotationLog(joinPoint);
        if (controllerLog == null) {
            return;
        }
        SysOperLog operLog = new SysOperLog();
        // 操作狀態(tài)(0正常 1異常)
        operLog.setStatus(0);
        // 操作時間
        operLog.setOperTime(new Date());
        if (e != null) {
            operLog.setStatus(1);
            // IotLicenseException為本系統(tǒng)自定義的異常類,讀者若要獲取異常信息,請根據(jù)自身情況變通
            operLog.setErrorMsg(StringUtils.substring(((IotLicenseException) e).getMsg(), 0, 2000));
        }

        // UserUtils.getUri();獲取方法上的路徑 如:/login,本文實(shí)現(xiàn)方法如下:
        // 1、在攔截器中 String uri = request.getRequestURI();
        // 2、用ThreadLocal存放uri,UserUtils.setUri(uri);
        // 3、UserUtils.getUri();
        String uri = UserUtils.getUri();
        operLog.setUri(uri);
        // 處理注解上的參數(shù)
        getControllerMethodDescription(joinPoint, controllerLog, operLog);
        // 保存數(shù)據(jù)庫
        sysOperLogService.addOperlog(operLog.getTitle(), operLog.getBusinessType(), operLog.getUri(), operLog.getStatus(), operLog.getOptParam(), operLog.getErrorMsg(), operLog.getOperTime());
    }

    /**
     * 是否存在注解,如果存在就獲取,不存在則返回null
     * @param joinPoint
     * @return
     */
    private MyLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(MyLog.class);
        }
        return null;
    }

    /**
     * 獲取Controller層上MyLog注解中對方法的描述信息
     * @param joinPoint 切點(diǎn)
     * @param myLog 自定義的注解
     * @param operLog 操作日志實(shí)體類
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, MyLog myLog, SysOperLog operLog) {
        // 設(shè)置業(yè)務(wù)類型(0其它 1新增 2修改 3刪除)
        operLog.setBusinessType(myLog.businessType().ordinal());
        // 設(shè)置模塊標(biāo)題,eg:登錄
        operLog.setTitle(myLog.title());
        // 對方法上的參數(shù)進(jìn)行處理,處理完:userName=xxx,password=xxx
        String optParam = getAnnotationValue(joinPoint, myLog.optParam());
        operLog.setOptParam(optParam);

    }

    /**
     * 對方法上的參數(shù)進(jìn)行處理
     * @param joinPoint
     * @param name
     * @return
     */
    private String getAnnotationValue(JoinPoint joinPoint, String name) {
        String paramName = name;
        // 獲取方法中所有的參數(shù)
        Map<String, Object> params = getParams(joinPoint);
        // 參數(shù)是否是動態(tài)的:#{paramName}
        if (paramName.matches("^#\\{\\D*\\}")) {
            // 獲取參數(shù)名,去掉#{ }
            paramName = paramName.replace("#{", "").replace("}", "");
            // 是否是復(fù)雜的參數(shù)類型:對象.參數(shù)名
            if (paramName.contains(".")) {
                String[] split = paramName.split("\\.");
                // 獲取方法中對象的內(nèi)容
                Object object = getValue(params, split[0]);
                // 轉(zhuǎn)換為JsonObject
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
                // 獲取值
                Object o = jsonObject.get(split[1]);
                return String.valueOf(o);
            } else {// 簡單的動態(tài)參數(shù)直接返回
                StringBuilder str = new StringBuilder();
                String[] paraNames = paramName.split(",");
                for (String paraName : paraNames) {
                    
                    String val = String.valueOf(getValue(params, paraName));
                    // 組裝成 userName=xxx,password=xxx,
                    str.append(paraName).append("=").append(val).append(",");
                }
                // 去掉末尾的,
                if (str.toString().endsWith(",")) {
                    String substring = str.substring(0, str.length() - 1);
                    return substring;
                } else {
                    return str.toString();
                }
            }
        }
        // 非動態(tài)參數(shù)直接返回
        return name;
    }

    /**
     * 獲取方法上的所有參數(shù),返回Map類型, eg: 鍵:"userName",值:xxx  鍵:"password",值:xxx
    * @param joinPoint
     * @return
     */
    public Map<String, Object> getParams(JoinPoint joinPoint) {
        Map<String, Object> params = new HashMap<>(8);
        // 通過切點(diǎn)獲取方法所有參數(shù)值["zhangsan", "123456"]
        Object[] args = joinPoint.getArgs();
        // 通過切點(diǎn)獲取方法所有參數(shù)名 eg:["userName", "password"]
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] names = signature.getParameterNames();
        for (int i = 0; i < args.length; i++) {
            params.put(names[i], args[i]);
        }
        return params;
    }

    /**
     * 從map中獲取鍵為paramName的值,不存在放回null
     * @param map
     * @param paramName
     * @return
     */
    private Object getValue(Map<String, Object> map, String paramName) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getKey().equals(paramName)) {
                return entry.getValue();
            }
        }
        return null;
    }
}

5、MyLog注解的使用

@GetMapping("login")
@MyLog(title = "登錄", optParam = "#{userName},#{password}", businessType = BusinessType.OTHER)
public DataResult login(@RequestParam("userName") String userName, @RequestParam("password") String password) {
 ...
}

6、最終效果

三、總結(jié)

用戶操作日志是AOP最常見的一種業(yè)務(wù)場景,這里只是簡單記錄了少量信息,如果需要更詳細(xì)的信息,就需要讀者自行去組裝和改造。

到此這篇關(guān)于Spring Boot+Aop記錄用戶操作日志的文章就介紹到這了,更多相關(guān)Spring Boot Aop記錄用戶操作日志內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決SpringBoot整合RocketMQ遇到的坑

    解決SpringBoot整合RocketMQ遇到的坑

    這篇文章主要介紹了解決SpringBoot整合RocketMQ遇到的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • JDBC基礎(chǔ)教程

    JDBC基礎(chǔ)教程

    這篇文章主要介紹了JDBC基礎(chǔ)知識與操作技巧,講述原理與基本技巧的基礎(chǔ)上分析了安全問題與操作注意事項(xiàng),非常具有實(shí)用價值,需要的朋友可以參考下
    2014-12-12
  • java中使用map排序的實(shí)例講解

    java中使用map排序的實(shí)例講解

    在本篇文章里小編給大家整理了一篇關(guān)于java中使用map排序的實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2020-12-12
  • Java實(shí)現(xiàn)在線五子棋對戰(zhàn)游戲(人機(jī)對戰(zhàn))

    Java實(shí)現(xiàn)在線五子棋對戰(zhàn)游戲(人機(jī)對戰(zhàn))

    這篇文章主要為大家詳細(xì)介紹了如何利用Java語言實(shí)現(xiàn)在線五子棋對戰(zhàn)游戲(人機(jī)對戰(zhàn)),文中的實(shí)現(xiàn)步驟講解詳細(xì),感興趣的可以嘗試一下
    2022-09-09
  • Java Set簡介_動力節(jié)點(diǎn)Java學(xué)院整理

    Java Set簡介_動力節(jié)點(diǎn)Java學(xué)院整理

    Set最大的特性就是不允許在其中存放的元素是重復(fù)的。接下來通過本文給大家分享java set常用方法和原理分析,需要的的朋友參考下吧
    2017-05-05
  • SpringBoot RestTemplate 簡單包裝解析

    SpringBoot RestTemplate 簡單包裝解析

    這篇文章主要介紹了SpringBoot RestTemplate 簡單包裝解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • spring中bean的生命周期詳解

    spring中bean的生命周期詳解

    今天小編就為大家分享一篇關(guān)于spring中bean的生命周期詳解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Myeclipse部署Tomcat_動力節(jié)點(diǎn)Java學(xué)院整理

    Myeclipse部署Tomcat_動力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章給大家介紹了Myeclipse部署Tomcat的相關(guān)知識,非常不錯,具有參考借鑒價值,需要的的朋友參考下吧
    2017-07-07
  • java 關(guān)鍵字static詳細(xì)介紹及如何使用

    java 關(guān)鍵字static詳細(xì)介紹及如何使用

    這篇文章主要介紹了java 關(guān)鍵字static詳細(xì)介紹及如何使用的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • SpringBoot集成Redis數(shù)據(jù)庫,實(shí)現(xiàn)緩存管理

    SpringBoot集成Redis數(shù)據(jù)庫,實(shí)現(xiàn)緩存管理

    SpringBoot2 版本,支持的組件越來越豐富,對Redis的支持不僅僅是擴(kuò)展了API,更是替換掉底層Jedis的依賴,換成Lettuce。 本案例需要本地安裝一臺Redis數(shù)據(jù)庫。下面就來看下集成Redis的步驟
    2021-06-06

最新評論