天天看点

Java ThreadLocal应用实例 获取方法运行时间

之前写了一个AOP形式发送日志给Kafka的demo

日志中有一个字段-获取方法运行时间

这个要求看起来简单(其实也简单)

在高并发的情况下不能使用普通变量long

使用ThreadLocal更合适(防止同时多次请求时数据被改变)

public final static ThreadLocal<Long> s = new ThreadLocal<>();

    @Before("@annotation(systemLog)")
    public void addTime(SystemLog systemLog) {
        this.s.set(System.currentTimeMillis());
    }

    @After("@annotation(systemLog)")
    public void Log(SystemLog systemLog){
    	System.out.println(System.currentTimeMillis() - this.s.get())
    }