Hello大家好,本章我們新增aop非同步記錄日誌功能 。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝
一:新增AOP依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>複製程式碼
二:建立自定義註解和切面
建立core→aop資料夾
在aop資料夾下中建立註解,其中remark為記錄的備註
package com.example.demo.core.aop;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotationLog {
String remark() default "";
}複製程式碼
建立切面
注:關於SystemLog
類,之前整合generator自動生成model,xml,dao功能這篇文章提到過的,忘記的可以再去看一下
package com.example.demo.core.aop;
import com.alibaba.fastjson.JSON;
import com.example.demo.core.systemlog.SystemLogQueue;
import com.example.demo.core.ret.ServiceException;
import com.example.demo.core.utils.ApplicationUtils;
import com.example.demo.model.SystemLog;
import com.example.demo.model.UserInfo;
import com.example.demo.service.SystemLogService;
import org.apache.ibatis.javassist.*;
import org.apache.ibatis.javassist.bytecode.CodeAttribute;
import org.apache.ibatis.javassist.bytecode.LocalVariableAttribute;
import org.apache.ibatis.javassist.bytecode.MethodInfo;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @Description: aop記錄操作日誌
* @author 張瑤
* @date 2018年5月28日 18:43:28
*/
@Aspect
@Component
public class AspectLog {
private static final Logger logger = LoggerFactory.getLogger(AspectLog.class);
@Resource
private SystemLogService systemLogService;
/**
* 定義切點
*/
@Pointcut("@annotation(com.example.demo.core.aop.AnnotationLog)")
public void methodCachePointcut() {
}
@Before("methodCachePointcut()")
public void doBefore(JoinPoint p) throws Exception{
SystemLog systemLog = getSystemLogInit(p);
systemLog.setLogType(SystemLog.LOGINFO);
systemLogService.insert(systemLog);
}
/**
* 呼叫後的異常處理
* @param p
* @param e
*/
@AfterThrowing(pointcut = "methodCachePointcut()", throwing = "e")
public void doAfterThrowing(JoinPoint p, Throwable e) throws Throwable {
//業務異常不用記錄
if(!(e instanceof ServiceException)) {
try {
SystemLog systemLog =getSystemLogInit(p);
systemLog.setLogType(SystemLog.LOGERROR);
systemLog.setExceptionCode(e.getClass().getName());
systemLog.setExceptionDetail(e.getMessage());
systemLogService.insert(systemLog);
} catch (Exception ex) {
logger.error("==異常通知異常==");
logger.error("異常資訊:{}", ex.getMessage());
}
}
}
private SystemLog getSystemLogInit(JoinPoint p){
SystemLog systemLog = new SystemLog();
try{
//類名
String targetClass = p.getTarget().getClass().toString();
//請求的方法名
String tartgetMethod = p.getSignature().getName();
//獲取類名 UserController
String classType = p.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
//請求引數名+引數值的map
Map<String, Object> nameAndArgs = getFieldsName(this.getClass(), clazzName, tartgetMethod, p.getArgs());
systemLog.setId(ApplicationUtils.getUUID());
systemLog.setDescription(getMthodRemark(p));
systemLog.setMethod(targetClass+"."+tartgetMethod);
//大家可自行百度獲取ip的方法
systemLog.setRequestIp("192.168.1.104");
systemLog.setParams(JSON.toJSONString(nameAndArgs));
systemLog.setUserId(getUserId());
systemLog.setCreateTime(new Date());
}catch (Exception ex){
logger.error("==異常通知異常==");
logger.error("異常資訊:{}", ex.getMessage());
}
return systemLog;
}
/**
* 通過反射機制 獲取被切引數名以及引數值
*
* @param cls
* @param clazzName
* @param methodName
* @param args
* @return
* @throws NotFoundException
*/
private Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map<String, Object> map = new HashMap<>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++) {
//HttpServletRequest 和HttpServletResponse 不做處理
if(!(args[i] instanceof HttpServletRequest || args[i] instanceof HttpServletResponse)){
//paramNames即引數名
map.put(attr.variableName(i + pos), JSON.toJSONString(args[i]));
}
}
return map;
}
/**
* 獲取方法的中文備註____用於記錄使用者的操作日誌描述
* @param joinPoint
* @return
* @throws Exception
*/
private static String getMthodRemark(JoinPoint joinPoint) throws Exception {
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] method = targetClass.getMethods();
String methode = "";
for (Method m : method) {
if (m.getName().equals(methodName)) {
Class[] tmpCs = m.getParameterTypes();
if (tmpCs.length == arguments.length) {
AnnotationLog methodCache = m.getAnnotation(AnnotationLog.class);
if (methodCache != null) {
methode = methodCache.remark();
}
break;
}
}
}
return methode;
}
private static String getUserId() {
String userId = "";
UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
if(userInfo != null){
userId = userInfo.getId();
}
return userId;
}
}複製程式碼
三:用法
在UserInfoController的selectById上新增我們剛建立的註解
@PostMapping("/selectById")
@AnnotationLog(remark = "查詢")
public RetResult<UserInfo> selectById(@RequestParam String id) {
UserInfo userInfo = userInfoService.selectById(id);
return RetResponse.makeOKRsp(userInfo);
}複製程式碼
四:測試
輸入localhost:8080/userInfo/selectById
拿到結果
檢視資料庫System_log
可以看到我們的日誌
五:優化
我們知道,日誌系統主要是方便我們分析程式,定位異常的。但是對於使用者來說,使用者一點都不在乎,所以我們不能因為需要記錄日誌,而延長使用者的等待時間,所以,這裡我們建立佇列來非同步執行記錄日誌操作
1:建立批量新增方法
SystemLogMapper.xml
<insert id="insertByBatch" parameterType="java.util.List" >
insert into system_log (
id, description, method, log_type, request_ip, exception_code,
exception_detail, params, user_id, create_time
)
values
<foreach collection="list" item="item" index= "index" separator =",">
(
#{item.id,jdbcType=VARCHAR},
#{item.description,jdbcType=VARCHAR},
#{item.method,jdbcType=VARCHAR},
#{item.logType,jdbcType=VARCHAR},
#{item.requestIp,jdbcType=VARCHAR},
#{item.exceptionCode,jdbcType=VARCHAR},
#{item.exceptionDetail,jdbcType=VARCHAR},
#{item.params,jdbcType=VARCHAR},
#{item.userId,jdbcType=VARCHAR},
#{item.createTime,jdbcType=TIMESTAMP}
)
</foreach>複製程式碼
SystemLogMapper.java
Integer insertByBatch(List<SystemLog> list);複製程式碼
Service層可參考碼雲地址,這裡就不做示例
2:建立日誌的存放佇列
建立core→systemlog資料夾
在該資料夾下建立SystemLogQueue
package com.example.demo.core.systemlog;
import com.example.demo.model.SystemLog;
import org.springframework.stereotype.Component;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
@Component
public class SystemLogQueue {
private BlockingQueue<SystemLog> blockingQueue = new LinkedBlockingQueue<>();
public void add(SystemLog systemLog) {
blockingQueue.add(systemLog);
}
public SystemLog poll() throws InterruptedException {
return blockingQueue.poll(1, TimeUnit.SECONDS);
}
}
複製程式碼
3:建立日誌佇列的消費者
package com.example.demo.core.systemlog;
import com.example.demo.model.SystemLog;
import com.example.demo.service.SystemLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Component
public class SystemLogConsumer implements Runnable{
private static Logger logger = LoggerFactory.getLogger(SystemLogConsumer.class);
public static final int DEFAULT_BATCH_SIZE = 64;
private SystemLogQueue auditLogQueue;
private SystemLogService systemLogService;
private int batchSize = DEFAULT_BATCH_SIZE;
private boolean active = true;
private Thread thread;
@PostConstruct
public void init() {
thread = new Thread(this);
thread.start();
}
@PreDestroy
public void close() {
active = false;
}
@Override
public void run() {
while (active) {
execute();
}
}
public void execute() {
List<SystemLog> systemLogs = new ArrayList<>();
try {
int size = 0;
while (size < batchSize) {
SystemLog systemLog = auditLogQueue.poll();
if (systemLog == null) {
break;
}
systemLogs.add(systemLog);
size++;
}
} catch (Exception ex) {
logger.info(ex.getMessage(), ex);
}
if (!systemLogs.isEmpty()) {
try {
//休眠10秒來模擬業務複雜,正在計算,測試之後大家別忘記刪除這句話
Thread.sleep(10000);
systemLogService.insertByBatch(systemLogs);
}catch (Exception e){
logger.error("異常資訊:{}", e.getMessage());
}
}
}
@Resource
public void setAuditLogQueue(SystemLogQueue auditLogQueue) {
this.auditLogQueue = auditLogQueue;
}
@Resource
public void setAuditLogService(SystemLogService systemLogService) {
this.systemLogService = systemLogService;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
}
複製程式碼
4:修改切面AspectLog
將:
@Resource
private SystemLogService systemLogService;複製程式碼
修改為:
@Resource
private SystemLogQueue systemLogQueue;複製程式碼
將:
systemLogQueue.insert(systemLog);複製程式碼
修改為:
systemLogQueue.add(systemLog);複製程式碼
5:測試
輸入localhost:8080/userInfo/selectById
注意:這裡是立刻返回結果,並沒有等待10秒,10秒之後開啟資料庫,得到我們剛操作的日誌
專案地址
碼雲地址: gitee.com/beany/mySpr…
GitHub地址: github.com/MyBeany/myS…
寫文章不易,如對您有幫助,請幫忙點下star
結尾
新增aop非同步記錄日誌功能已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。