最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

通過(guò)AOP攔截Spring?Boot日志并將其存入數(shù)據(jù)庫(kù)功能實(shí)現(xiàn)

 更新時(shí)間:2023年08月30日 08:30:20   作者:華為云開(kāi)發(fā)者聯(lián)盟  
本文介紹了如何使用Spring Boot和AOP技術(shù)實(shí)現(xiàn)攔截系統(tǒng)日志并保存到數(shù)據(jù)庫(kù)中的功能,包括配置數(shù)據(jù)庫(kù)連接、定義日志實(shí)體類(lèi)、定義日志攔截器、使用AOP攔截日志并保存到數(shù)據(jù)庫(kù)中等步驟,感興趣的朋友一起看看吧

本文將介紹如何使用Spring Boot和AOP技術(shù)實(shí)現(xiàn)攔截系統(tǒng)日志并保存到數(shù)據(jù)庫(kù)中的功能。

本文分享自華為云社區(qū)《Spring Boot入門(mén)(23):【實(shí)戰(zhàn)】通過(guò)AOP攔截Spring Boot日志并將其存入數(shù)據(jù)庫(kù)》,作者:bug菌。

前言

在軟件開(kāi)發(fā)中,常常需要記錄系統(tǒng)運(yùn)行時(shí)的日志。日志記錄有助于排查系統(tǒng)問(wèn)題、優(yōu)化系統(tǒng)性能、監(jiān)控操作行為等。本文將介紹如何使用Spring Boot和AOP技術(shù)實(shí)現(xiàn)攔截系統(tǒng)日志并保存到數(shù)據(jù)庫(kù)中的功能。

摘要

本文將通過(guò)以下步驟實(shí)現(xiàn)攔截系統(tǒng)日志并保存到數(shù)據(jù)庫(kù)中的功能:

  • 配置數(shù)據(jù)庫(kù)連接
  • 定義日志實(shí)體類(lèi)
  • 定義日志攔截器
  • 使用AOP攔截日志并保存到數(shù)據(jù)庫(kù)中

AOP介紹

AOP,全稱(chēng)是Aspect Oriented Programming,即面向切面編程。AOP的目的是將那些與業(yè)務(wù)無(wú)關(guān),但是業(yè)務(wù)模塊都需要的功能,如日志統(tǒng)計(jì)、安全控制、事務(wù)處理等,封裝成可重用的組件,從而將它們從業(yè)務(wù)邏輯代碼中劃分出來(lái),編寫(xiě)成獨(dú)立的切面。這樣做,既可以保持業(yè)務(wù)邏輯的純凈和高內(nèi)聚性,又可以使得系統(tǒng)的多個(gè)模塊都可以共享這些公共的功能。

Spring框架提供了對(duì)AOP的支持,Spring Boot自然也不例外。使用Spring Boot的AOP功能,我們可以在運(yùn)行時(shí)動(dòng)態(tài)地將代碼橫向切入到各個(gè)關(guān)注點(diǎn)(方法或者類(lèi))中。這種橫向切面的方式,比傳統(tǒng)的縱向切面(繼承)更加靈活。

AOP的實(shí)現(xiàn)

添加依賴(lài)

在pom.xml中添加以下依賴(lài):

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

這樣我們就可以使用Spring Boot的AOP功能和MyBatis框架。

配置數(shù)據(jù)庫(kù)連接

首先需要在Spring Boot項(xiàng)目的application.properties文件中配置數(shù)據(jù)庫(kù)連接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

或者你也可以使用YAML的配置格式:

定義日志實(shí)體類(lèi)

定義一個(gè)Log實(shí)體類(lèi)用于保存日志信息,并使用@Entity和@Table注解指定對(duì)應(yīng)的數(shù)據(jù)庫(kù)表和字段:

@Entity
@Table(name = "sys_log")
public class Log {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String operation;
private String method;
private String params;
private String ip;
private Date createTime;
// 省略getter和setter方法
}

定義日志攔截器

定義一個(gè)日志攔截器LogInterceptor,通過(guò)實(shí)現(xiàn)HandlerInterceptor接口來(lái)攔截請(qǐng)求并記錄日志:

@Component
public class LogInterceptor implements HandlerInterceptor {
@Autowired
private LogRepository logRepository;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 獲取請(qǐng)求的IP地址
String ip = getIpAddress(request);
// 獲取當(dāng)前用戶(hù)
String username = getCurrentUsername();
// 獲取請(qǐng)求的方法名
String method = request.getMethod();
// 獲取請(qǐng)求的URL
String url = request.getRequestURI();
// 獲取請(qǐng)求的參數(shù)
String params = getParams(request);
// 創(chuàng)建日志實(shí)體
Log log = new Log();
log.setIp(ip);
log.setMethod(method);
log.setOperation("訪問(wèn)");
log.setParams(params);
log.setUsername(username);
log.setCreateTime(new Date());
// 保存日志到數(shù)據(jù)庫(kù)中
logRepository.save(log);
return true;
}
// 省略實(shí)現(xiàn)HandlerInterceptor接口的其他方法
/**
* 獲取請(qǐng)求的IP地址
*/
private String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 獲取當(dāng)前用戶(hù)
*/
private String getCurrentUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
return authentication.getName();
}
return null;
}
/**
* 獲取請(qǐng)求的參數(shù)
*/
private String getParams(HttpServletRequest request) {
Map<String, String[]> parameterMap = request.getParameterMap();
if (parameterMap == null || parameterMap.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
sb.append(entry.getKey()).append("=").append(Arrays.toString(entry.getValue())).append("&");
}
return sb.toString();
}
}

使用AOP攔截日志并保存到數(shù)據(jù)庫(kù)中

使用AOP技術(shù)攔截所有Controller類(lèi)中的方法,并執(zhí)行LogInterceptor中的preHandle方法,記錄日志并保存到數(shù)據(jù)庫(kù)中。

定義一個(gè)LogAspect切面類(lèi),通過(guò)實(shí)現(xiàn)@Aspect注解和@Before注解來(lái)實(shí)現(xiàn)方法攔截:

@Aspect
@Component
public class LogAspect {
@Autowired
private LogInterceptor logInterceptor;
@Pointcut("execution(public * com.example.demo.controller..*.*(..))")
public void logAspect() {}
@Before("logAspect()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return;
}
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
HandlerMethod handlerMethod = (HandlerMethod) joinPoint.getSignature();
try {
logInterceptor.preHandle(request, response, handlerMethod);
} catch (Exception e) {
e.printStackTrace();
}
}
}

代碼方法介紹

  • LogInterceptor.preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)方法:攔截請(qǐng)求并記錄日志的方法。
  • LogInterceptor.getIpAddress(HttpServletRequest request)方法:獲取請(qǐng)求的IP地址。
  • LogInterceptor.getCurrentUsername()方法:獲取當(dāng)前用戶(hù)。
  • LogInterceptor.getParams(HttpServletRequest request)方法:獲取請(qǐng)求的參數(shù)。
  • LogAspect.logAspect()方法:定義AOP切入點(diǎn),攔截Controller類(lèi)中的所有方法。
  • LogAspect.doBefore(JoinPoint joinPoint)方法:執(zhí)行方法攔截操作,并調(diào)用LogInterceptor.preHandle方法來(lái)記錄日志。

測(cè)試用例

可以使用Postman等工具發(fā)起請(qǐng)求來(lái)測(cè)試攔截器是否生效,并查看數(shù)據(jù)庫(kù)中是否保存了對(duì)應(yīng)的日志信息。這里就不直接演示了,畢竟使用起來(lái)非常的簡(jiǎn)單易上手。

全文小結(jié)

本文介紹了如何使用Spring Boot和AOP技術(shù)實(shí)現(xiàn)攔截系統(tǒng)日志并保存到數(shù)據(jù)庫(kù)中的功能,包括配置數(shù)據(jù)庫(kù)連接、定義日志實(shí)體類(lèi)、定義日志攔截器、使用AOP攔截日志并保存到數(shù)據(jù)庫(kù)中等步驟。通過(guò)本文的介紹,可以更好地理解Spring Boot和AOP的應(yīng)用,為開(kāi)發(fā)高效、穩(wěn)定的系統(tǒng)提供參考。

注:

環(huán)境說(shuō)明:Windows10 + Idea2021.3.2 + Jdk1.8 + SpringBoot 2.3.1.RELEASE

到此這篇關(guān)于通過(guò)AOP攔截Spring Boot日志并將其存入數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)AOP攔截Spring Boot日志內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot使用JavaCV處理rtsp流的示例代碼

    SpringBoot使用JavaCV處理rtsp流的示例代碼

    這篇文章主要為大家詳細(xì)介紹了SpringBoot使用JavaCV處理rtsp流,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以跟隨小編一起了解一下
    2024-02-02
  • 一文解析SpringBoot到底強(qiáng)在哪

    一文解析SpringBoot到底強(qiáng)在哪

    SpringBoot是基于Spring框架的快速開(kāi)發(fā)腳手架,采用約定優(yōu)于配置的理念,讓開(kāi)發(fā)者能夠快速創(chuàng)建獨(dú)立運(yùn)行、生產(chǎn)級(jí)的Spring應(yīng)用程序,它通過(guò)簡(jiǎn)化配置和自動(dòng)裝配機(jī)制,大幅減少了傳統(tǒng)Spring應(yīng)用開(kāi)發(fā)中的樣板代碼,下面通過(guò)本文解析SpringBoot到底強(qiáng)在哪,感興趣的朋友一起看看吧
    2026-01-01
  • Java利用ElasticSearch實(shí)現(xiàn)增刪改功能

    Java利用ElasticSearch實(shí)現(xiàn)增刪改功能

    這篇文章主要為大家詳細(xì)介紹了Java如何利用ElasticSearch實(shí)現(xiàn)增刪改功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-08-08
  • MapStruct到底是什么?

    MapStruct到底是什么?

    今天給大家?guī)?lái)的是關(guān)于Java的相關(guān)知識(shí),文中圍繞MapStruct到底是什么展開(kāi),文中有非常詳細(xì)的解釋及代碼示例,需要的朋友可以參考下
    2021-06-06
  • Java實(shí)現(xiàn)反轉(zhuǎn)一個(gè)鏈表的示例代碼

    Java實(shí)現(xiàn)反轉(zhuǎn)一個(gè)鏈表的示例代碼

    本文主要介紹了Java實(shí)現(xiàn)反轉(zhuǎn)一個(gè)鏈表的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • java堆棧類(lèi)使用實(shí)例(java中stack的使用方法)

    java堆棧類(lèi)使用實(shí)例(java中stack的使用方法)

    java中stack的使用方法,堆棧是一種"后進(jìn)先出"(LIFO) 的數(shù)據(jù)結(jié)構(gòu), 只能在一端進(jìn)行插入(稱(chēng)為"壓棧") 或刪除 (稱(chēng)為"出棧")數(shù)據(jù)的操作,下面看示例吧
    2013-12-12
  • 最新評(píng)論

    思茅市| 漯河市| 搜索| 富裕县| 会同县| 临漳县| 三门峡市| 卫辉市| 巢湖市| 渑池县| 昌宁县| 灌云县| 怀化市| 柯坪县| 旅游| 双江| 鄂温| 长岭县| 白城市| 大埔区| 张家口市| 衡阳县| 青田县| 桓仁| 新民市| 共和县| 凤山市| 弥渡县| 安福县| 巴塘县| 吉木乃县| 阳春市| 鄂伦春自治旗| 泰和县| 余江县| 滦南县| 邢台市| 花莲县| 庄浪县| 洛浦县| 眉山市|