注解
import org.springframework.stereotype.Service;
import java.lang.annotation.*;
/**
* @Author:Aden.WeiHao
* @Date:2023/2/24 11:23
*/
@Service
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MessageExceptionAnnotation {
public String value() default "";
}
切面
package com.spotter.message.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
@Aspect
@Component
@Slf4j
public class MessageConsumerPointcut {
@Autowired
DingTalkSendManager dingTalkSendManager;
@Pointcut("@annotation(com.spotter.message.adapter.annotation.MessageExceptionAnnotation)")
public void pointCut() {
}
@Around("pointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
MessageExceptionAnnotation logAlarm = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(MessageExceptionAnnotation.class);
String content = logAlarm.value() + ":{类:" + className + "},{方法:" + methodName + "},发生异常:";
Object[] args = joinPoint.getArgs();
StringBuffer params = new StringBuffer();
for (Object arg : args) {
params.append(arg).append(",");
}
log.info("开始执行" + className + "的" + methodName + "入参为:" + params.toString());
Object proceed = null;
try {
proceed = joinPoint.proceed();
} catch (Throwable e) {
log.error(content, e);
System.out.println("--------========");
//钉钉群告警
//AlarmUtils.DingNotice(content + e);
}
log.info(className + "的" + methodName + "执行结束!");
return proceed;
}
private String buildSimpleMessage(ProceedingJoinPoint proceedingJoinPoint, MessageResultDTO messageResultDTO) {
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
Object[] args = proceedingJoinPoint.getArgs();
return " **服务名称:** " + MessageContextHandler.getApplicationName() + "\n\n" +
" **时间:** " + DateUtils.getNowDateTime() + "\n\n" +
" **方法名称:** " + method.getName() + "\n\n" +
" **异常信息:** " + messageResultDTO.getMessage() + "\n\n" +
" **参数信息:**" + Arrays.asList(args);
}
}
使用
@MessageExceptionAnnotation("xxxxxxxx")
public void run(){}