我使用Spring AOP實現了用戶操作日誌功能

来源:https://www.cnblogs.com/Fzeng/archive/2022/05/21/16294977.html
-Advertisement-
Play Games

我使用Spring AOP實現了用戶操作日誌功能 今天答辯完了,復盤了一下系統,發現還是有一些東西值得拿出來和大家分享一下。 需求分析 系統需要對用戶的操作進行記錄,方便未來溯源 首先想到的就是在每個方法中,去實現記錄的邏輯,但是這樣做肯定是不現實的,首先工作量大,其次違背了軟體工程設計原則(開閉原 ...


我使用Spring AOP實現了用戶操作日誌功能

今天答辯完了,復盤了一下系統,發現還是有一些東西值得拿出來和大家分享一下。

需求分析

系統需要對用戶的操作進行記錄,方便未來溯源

首先想到的就是在每個方法中,去實現記錄的邏輯,但是這樣做肯定是不現實的,首先工作量大,其次違背了軟體工程設計原則(開閉原則)

這種需求顯然是對代碼進行增強,首先想到的是使用 SpringBoot 提供的 AOP 結合註解的方式來實現

功能實現

1、 需要一張記錄日誌的 Log 表

image-20220521134019891

導出的 sql 如下:

-- mcams.t_log definition

CREATE TABLE `t_log` (
  `log_id` int NOT NULL AUTO_INCREMENT COMMENT '日誌編號',
  `user_id` int NOT NULL COMMENT '操作人id',
  `operation` varchar(128) NOT NULL COMMENT '用戶操作',
  `method` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '操作的方法',
  `params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法的參數',
  `ip` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '用戶的ip',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '操作時間',
  `cost_time` int DEFAULT NULL COMMENT '花費時間',
  PRIMARY KEY (`log_id`)
) ENGINE=InnoDB AUTO_INCREMENT=189 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

2、我使用的是 Spring Boot 所以需要引入 spring aop 的 starter

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

如果是使用 spring 框架的,引入 spring-aop 即可

3、Log 實體類

package com.xiaofengstu.mcams.web.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;

/**
 * <p>
 * 
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-21
 */
@Getter
@Setter
@TableName("t_log")
public class TLog implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "log_id", type = IdType.AUTO)
    private Integer logId;

    /**
     * 操作人id
     */
    @TableField("user_id")
    private Integer userId;

    /**
     * 用戶操作
     */
    @TableField("operation")
    private String operation;


    @TableField("method")
    private String method;

    @TableField("params")
    private String params;

    @TableField("ip")
    private String ip;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @TableField("create_time")
    private LocalDateTime createTime;

    @TableField("cost_time")
    private Long costTime;


}

需要 lombok 插件(@getter && @setter 註解)

4、ILog 註解

package com.xiaofengstu.mcams.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author FengZeng
 * @Date 2022-05-21 00:48
 * @Description TODO
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ILog {
  String value() default "";
}

5、切麵類 LogAspect

package com.xiaofengstu.mcams.aspect;

import com.xiaofengstu.mcams.annotation.ILog;
import com.xiaofengstu.mcams.util.ThreadLocalUtils;
import com.xiaofengstu.mcams.web.entity.TLog;
import com.xiaofengstu.mcams.web.service.TLogService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @Author FengZeng
 * @Date 2022-05-21 00:42
 * @Description TODO
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
  private final TLogService logService;

  @Pointcut("@annotation(com.xiaofengstu.mcams.annotation.ILog)")
  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 costTime = System.currentTimeMillis() - beginTime;

    saveLog(point, costTime);

    return result;
  }

  private void saveLog(ProceedingJoinPoint point, long costTime) {
    // 通過 point 拿到方法簽名
    MethodSignature methodSignature = (MethodSignature) point.getSignature();
    // 通過方法簽名拿到被調用的方法
    Method method = methodSignature.getMethod();

    TLog log = new TLog();
    // 通過方法區獲取方法上的 ILog 註解
    ILog logAnnotation = method.getAnnotation(ILog.class);
    if (logAnnotation != null) {
      log.setOperation(logAnnotation.value());
    }

    String className = point.getTarget().getClass().getName();
    String methodName = methodSignature.getName();
    log.setMethod(className + "." + methodName + "()");

    // 獲取方法的參數
    Object[] args = point.getArgs();
    LocalVariableTableParameterNameDiscoverer l = new LocalVariableTableParameterNameDiscoverer();
    String[] parameterNames = l.getParameterNames(method);
    if (args != null && parameterNames != null) {
      StringBuilder param = new StringBuilder();
      for (int i = 0; i < args.length; i++) {
        param.append(" ").append(parameterNames[i]).append(":").append(args[i]);
      }
      log.setParams(param.toString());
    }

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    log.setIp(request.getRemoteAddr());

    log.setUserId(ThreadLocalUtils.get());
    log.setCostTime(costTime);
    log.setCreateTime(LocalDateTime.now());

    logService.save(log);
  }

}

因為我使用的是 Mybatis-plus,所以 logService.save(log);是 mybatis-plus 原生的 save operation

這步其實就是把 log 插入到資料庫

6、使用

只需要在方法上加上 @ILog 註解,並設置它的 value 即可(value 就是描述當前 method 作用)

package com.xiaofengstu.mcams.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaofengstu.mcams.annotation.ILog;
import com.xiaofengstu.mcams.dto.BasicResultDTO;
import com.xiaofengstu.mcams.enums.RespStatusEnum;
import com.xiaofengstu.mcams.web.entity.TDept;
import com.xiaofengstu.mcams.web.service.TDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author fengzeng
 * @since 2022-05-07
 */
@RestController
@RequestMapping("/web/dept")
@RequiredArgsConstructor
public class TDeptController {

  private final TDeptService deptService;

  @ILog("獲取部門列表")
  @GetMapping("/list")
  public BasicResultDTO<List<TDept>> getDeptListByCampId(@RequestParam("campusId") Integer campusId) {
    return new BasicResultDTO(RespStatusEnum.SUCCESS, deptService.list(new QueryWrapper<TDept>().eq("campus_id", campusId)));
  }

  @ILog("通過角色獲取部門列表")
  @GetMapping("/listByRole")
  public BasicResultDTO<List<TDept>> getDeptListByRole() {
    return new BasicResultDTO<>(RespStatusEnum.SUCCESS, deptService.listByRole());
  }

}

資料庫:

image-20220521135144910

總結

如果要對現有代碼進行功能擴展,使用 AOP + 註解不妨為一種優雅的方式

對 AOP 不熟悉的小伙伴,可以深入瞭解一下,畢竟是 spring 最重要的特性之一。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 摘要:本篇我們將以分析歷史股價為例,介紹怎樣從文件中載入數據,以及怎樣使用NumPy的基本數學和統計分析函數、學習讀寫文件的方法,並嘗試函數式編程和NumPy線性代數運算,來學習NumPy的常用函數。 一、文件讀入 :讀寫文件是數據分析的一項基本技能 CSV(Comma-Separated Valu ...
  • 轉載請註明出處❤️ 作者:IT小學生蔡坨坨 原文鏈接:https://www.caituotuo.top/a3a8d0c0.html 大家好,我是IT小學生蔡坨坨。 今天,我們來聊聊介面自動化測試是什麼?如何開始?介面自動化測試框架怎麼做? 自動化測試 自動化測試,這幾年行業內的熱詞,也是測試人員進 ...
  • 知識回顧 Bean的創建過程會經歷getBean,doGetBean,createBean,doCreateBean,然後Bean的創建又會經歷實例化,屬性填充,初始化。 在實例化createInstance時大致可以分為三種方式進行實例化: 使用Supplier 進行實例化,通過BeanFacto ...
  • 在上一篇文章《SpringBoot進階教程(七十三)整合elasticsearch 》,已經詳細介紹了關於elasticsearch的安裝與使用,現在主要來看看關於ELK的定義、安裝及使用。 v簡介 1.什麼是ELK? ELK 是elastic公司提供的一套完整的日誌收集以及展示的解決方案,是三個產 ...
  • 強轉int類型會直接對浮點數的小數部分進行截斷(無論是正還是負)。還有一種方法是math.ceil和math.floor。無論是正數還是負數,都遵循:ceil往數軸正方向取整,floor往數軸負方向取整。round原型為round(value, ndigits),可以將一個浮點數取整到固定的小數位。... ...
  • 很多人都喜歡使用黑色的主題樣式,包括我自己,使用了差不多三年的黑色主題,但是個人覺得在進行視窗轉換的時候很廢眼睛。 比如IDEA是全黑的,然後需要看PDF或者WORD又變成白色的了,這樣來回切換導致眼睛很累,畢竟現在網頁以及大部分軟體的界面都是白色的。那麼還是老老實實的使用原來比較順眼的模式吧。 1 ...
  • 本期教程人臉識別第三方平臺為虹軟科技,本文章講解的是人臉識別RGB活體追蹤技術,免費的功能很多可以自行搭配,希望在你看完本章課程有所收穫。 ...
  • 《零基礎學Java》 繪製幾何圖形 Java可以分別使用 Graphics 和 Graphics2D 繪製圖形,Graphics類 使用不同的方法繪製不同的圖形(drawLine()方法可f以繪製線、drawRect()方法用於繪製矩形、drawOval()方法用於繪製橢圓形)。 Graphics類 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...