是否有可能創建一個自定義注解,簡單地跟蹤一些方法的呼叫,而不必在每個方法顯式中添加一個服務方法呼叫?
@InvocationCounter(path = "/test1") //我正在尋找這個@GetMapping("/person/{id}")
public Person getPerson(Long id) {
//...。
}
在每次getPerson()呼叫時,我希望有一個呼叫計數器來記錄呼叫情況,例如:
@Service
public class InvocationCounterService {
Map<String, AtomicInteger> counter;
public void count(String path) {
if (counter.get(path) == null) counter.put(path, new AtomicInteger() )。
counter.get(path).incrementAndGet()。
}
@Scheduled(fixedRate = 60000)
public void persist() {
//可選擇處理或持久化呼叫。
}
}
問題:我怎樣才能告訴Spring在每個被注釋的控制器方法上呼叫count()服務方法呢?
uj5u.com熱心網友回復:
注解InvocationCounter:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InvocationCounter {
字串 path()。
}
Aspect InvocationCounterAspect:
@Aspect
@Component
public class InvocationCounterAspect {
@Autowired
InvocationCounterService invocationCounterService。
@Around("@annotation(InvocationCounter)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature)joinPoint.getSignature()。
InvocationCounter invocationCounter = signature.getMethod().getAnnotation(InvocationCounter.class)。
final String path = invocationCounter.path(); //從注釋中檢索路徑
invocationCounterService.count(path); //call the counter service。
return joinPoint.proceed(); //繼續執行注釋的方法。
}
uj5u.com熱心網友回復:
你應該看一下micrometer.io,Spring boot應用程式原生支持指標收集,包括簡單的計數器。
uj5u.com熱心網友回復:
注解是一種語法元資料的形式,可以添加到Java源代碼中。 所以你可以用注解向你的源代碼添加資訊,但你不能添加要執行的代碼。
您可以使用 pleft 在評論中提到的各個方面。
或者你可以創建一個 countExecutions 函式,將你的 Function 作為一個 lambda 運算式來計算執行的次數,如下所示:
public R countExecutions(Function<R, T> fun, T data) {
//呼叫計數器。
return fun.apply(data)。
}
并將你的代碼改寫成
@GetMapping("/person/{id}")
public Person getPerson(Long id) {
return countExecutions( /* code previously in the getPerson as a Function */ , id) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/313456.html
標籤:
