我的一个切面


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class SearchCenterHSFConsumerAspect {

private static final Logger logger = LoggerFactory.getLogger("hsf_monitor_log");


/**
* 用来记录请求进入的时间,防止多线程时出错
*/
private ThreadLocal<Long> startTime = new ThreadLocal<>();


/**
* 定义切入点,controller下面的所有类的所有公有方法
*/
@Pointcut("bean(user1Service) || bean(user2Service) || bean(user3Service) || bean(user4Service) || bean(user5Service)")
    public void point() {
}


/**
* 方法之前执行,日志打印请求信息
* @param joinPoint
*/
@Before("point()")
public void doBefore(JoinPoint joinPoint) {
logger.info("HSFConsumerRequest=" + getMethodNameAndArgs(joinPoint));
}


@After("point()")
public void doAfter() {
long endTime = System.currentTimeMillis();
logger.info("HSFConsumer doAfter");
}

/**
* 方法返回之前执行
* @param object
*/
@AfterReturning(returning = "object", pointcut = "point()")
public void doAfterReturning(JoinPoint joinPoint, Object object) {
logger.info("HSFConsumer doAfterReturning");
}

/**
* 获取方法名和参数
* @param joinPoint
* @return
*/
private String getMethodNameAndArgs(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
StringBuffer sb = new StringBuffer("HSFConsumerMethodName:");
sb.append(joinPoint.getSignature().getName() + "(");
for (int i = 0; i < args.length; i++) {
sb.append("HSFConsumerArg[" + i + "]: " + args[i] + ",");
}
if (args.length > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(")");
return sb.toString();
}

}

posted on 2021-07-29 15:07  小小鸟儿!  阅读(37)  评论(0编辑  收藏  举报