1. 程式人生 > >spring boot集成aop實現日誌記錄

spring boot集成aop實現日誌記錄

dst info pen reads image joinpoint 容器 asp call

1、pom依賴

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

2、切點定義

/**
* 利用切面記錄線程調用監控中心記錄
*
*/

//將bean註入spring容器
@Component

//開啟aop註解
@Aspect
public class ThreadCallRecoedAop {

public Logger logger = LoggerFactory
.getLogger(ThreadCallRecoedAop.class);// 輸出日誌
@Autowired
private RecordLogAsync recordLogAsync;
@Pointcut("execution(* com.sigmatrix.thread.controller.ReceiveThreadStateController.receive(..))")//切入點描
public void controllerLog(){}
/**
* 記錄線程調用監控中心日誌
* 在方法執行之前進行切面切入
*/

@Before("controllerLog()")
public void recordLog(JoinPoint pjp){
Object[] args;
try{
logger.info("-------------異步記錄日誌開始");

//獲取參數
args = pjp.getArgs();
ThreadStateRecord threadStateRecord=(ThreadStateRecord) args[0];

//進行異步日誌記錄,防止阻塞
recordLogAsync.insertThreadCallLog(threadStateRecord);

logger.info("-------------異步記錄日誌成功");
}catch(Throwable te){
logger.error("異步記錄日誌異常信息為:",te);
}
}

}

/**
* 異步記錄日誌入庫
*
*/
@Component
public class RecordLogAsync {
@Autowired
private ThreadCallRecordService threadCallRecordService;
/**
* 記錄線程調用監控中心日誌
*
*/
@Async
public void insertThreadCallLog(ThreadStateRecord threadStateRecord) throws Throwable{
ThreadCallRecord threadCallRecord =new ThreadCallRecord();
//記錄時間
threadCallRecord.setThreadCallTime(new Date());
//線程名字
threadCallRecord.setThreadName(threadStateRecord.getThreadName());
//調用監控中心線程配置信息
threadCallRecord.setCallMeaaage(threadStateRecord.getThreadCallMessage());
//線程狀態
threadCallRecord.setThreadState(threadStateRecord.getThreadMessage());
threadCallRecordService.insertSelective(threadCallRecord);
threadCallRecord =null;
}
}

3、開啟異步Async註解使用

技術分享圖片

spring boot集成aop實現日誌記錄