[英]How to extract telemetry code from different methods? Decorator pattern? AOP?
我們正在使用 Application Insights 來監控應用程序中的不同服務調用。 Application Insights 的數據由許多不同的方法和類提供,但始終以相同的方式/由相同的代碼片段提供:
public class MyClassA {
public void myMethodA() {
final Instant startTime = Instant.now();
try {
callSomeServiceA();
} catch (final Exception e) {
sendExceptionDataToAppInsights(e);
throw e;
} finally {
sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());
}
}
}
public class MyClassB {
public String myMethodB() {
final Instant startTime = Instant.now();
try {
return callSomeServiceB();
} catch (final Exception e) {
sendExceptionDataToAppInsights(e);
throw e;
} finally {
sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());
}
}
}
我如何能夠將那些包裝嘗試捕獲片段提取到一個責任點? 我看了一下 dacorator 模式,但我猜它不適合,因為方法簽名不同。 或者是嗎?
或者有沒有辦法用 AOP 來實現它?
面向方面的編程是模塊化橫切關注點的范例,例如日志記錄、監控和錯誤處理(您的特定情況)。
在 Java 中實現這一點的最流行的框架是AspectJ ,它可以通過spring-boot-starter-aop
依賴項從任何 Spring 項目中使用。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>${aop-version}</version>
</dependency>
implementation `org.springframework.boot:spring-boot-starter-aop:${aop-version}`
實現您所要求的最簡單的方法是制作一個使用@Around
的方面(使用@Aspect
)。 網上有很多這樣的例子。 您的執行( ProceedingJoinPoint
:: proceed
)將需要在 try-catch 塊內發生,這與您的問題非常相似:
@Around("execution(<aspectj-selector-here>)")
public void anyMethodName(ProceedingJoinPoint pjp) {
// try-catch blocks here...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.