通過添加註解 AOP 面向切面編程

第一步:創建註解類

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 註解實現AOP裝配
 * 檢測一個請求耗時情況
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface MetricTime {
    String value();
}

 

第二步:將註解加到想要監聽的方法上面

@GetMapping("/material")
@ApiOperation(value = "素材", notes = "素材 API")
@MetricTime("register")
public ApiResult cancelTopicTop(@RequestParam(value="pageNumber",required = false,defaultValue = "0") int pageNo,
        @RequestParam(value="pageSize",required = false,defaultValue = "10") int pageSize,
        @ApiParam(name = "kind", value = "種類:1:視頻 2:圖片", required = true) @RequestParam(value = "kind") Integer kind) {
    PageHelper.startPage(pageNo,pageSize);
    PageInfo<KeyValueVO> pageInfo = new PageInfo(topicService.getMaterial(kind));
    return new ApiResult().withData(pageInfo);
}

第三步:編寫具體的操作

import cn.com.community.admin.service.MetricTime;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @Author:zhuchuanshun
 * @Description: AOP 實現性能監控 一個請求耗時
 * @Date: 2020/6/22 11:08
 * @Modificd:
 */
@Aspect
@Component
public class MetricAspect {
    @Around("@annotation(metricTime)")
    public Object metric(ProceedingJoinPoint joinPoint, MetricTime metricTime) throws Throwable {
        String name = metricTime.value();
        long start = System.currentTimeMillis();
        try {
            return joinPoint.proceed();
        } finally {
            long t = System.currentTimeMillis() - start;
            // 寫入日誌或發送至JMX:
            System.out.println("該請求耗時 [Metrics] " + name + ": " + t + "ms");
        }
    }
}

這樣就只要在方法上面添加 @MetricTime("register") 註解,就可以看到 請求耗的時間。

這樣編寫邏輯,將耗時打印一定的接口,另外打印出來。

參考:https://www.liaoxuefeng.com/wiki/1252599548343744/1310052317134882

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章