Java 如何从不同的方法中提取遥测代码?装饰图案?AOP?

Java 如何从不同的方法中提取遥测代码?装饰图案?AOP?,java,spring-boot,design-patterns,aspectj,azure-application-insights,Java,Spring Boot,Design Patterns,Aspectj,Azure Application Insights,我们正在使用Application Insights监视应用程序中的不同服务调用。Application Insights的数据由许多不同的方法和类提供,但始终以相同的方式/由相同的代码片段提供: 公共类MyClassA{ 公共无效myMethodA(){ final Instant startTime=Instant.now(); 试一试{ callSomeServiceA(); }捕获(最终异常e){ 发送例外数据至Appsights(e); 投掷e; }最后{ senddatatoappi

我们正在使用Application Insights监视应用程序中的不同服务调用。Application Insights的数据由许多不同的方法和类提供,但始终以相同的方式/由相同的代码片段提供:

公共类MyClassA{
公共无效myMethodA(){
final Instant startTime=Instant.now();
试一试{
callSomeServiceA();
}捕获(最终异常e){
发送例外数据至Appsights(e);
投掷e;
}最后{
senddatatoappingsights(MyClass.getName(),myMethodA.getName(),startTime,Instant.now());
}
}
}
公共类MyClassB{
公共字符串myMethodB(){
final Instant startTime=Instant.now();
试一试{
返回callSomeServiceB();
}捕获(最终异常e){
发送例外数据至Appsights(e);
投掷e;
}最后{
senddatatoappingsights(MyClass.getName(),myMethodA.getName(),startTime,Instant.now());
}
}
}
我如何才能将这些包装碎片提取到一个责任点?我查看了dacorator模式,但我想它不适合,因为方法签名不同。还是这样?
或者有没有办法用AOP实现它?

是模块化横切关注点的范例,例如日志记录、监视和错误处理(您的特定情况)

在Java中实现这一点的最流行的框架是,它可以通过
springbootstarterAOP
依赖项从任何Spring项目中使用

专家

org.springframework.boot
::继续
)将需要在一个try-catch块中进行,与您的问题非常相似:

@Around(“execution()”)
public void anyMethodName(ProceedingJoinPoint pjp){
//试着在这里拦截。。。
}

这些类和方法之间有什么关系?它们之间实际上没有任何关系。它们甚至分布在不同的微服务中。也许你应该举一个实际的例子,因为你提供的例子不会编译。这是一个很好的观点,谢谢。但有没有办法将参数插入方面实现中?我需要将参数传递给
senddatatoappingsights
上的方法(我上面提到的
pjp
是aspect方法的一个参数)具有您所需的一切:)@PaulBenn如果您不喜欢编辑,可以自由回滚
implementation `org.springframework.boot:spring-boot-starter-aop:${aop-version}`