How to set up Spring Boot to make component metered without adding @Timed to each class, but rather specifying already used annotations like @Service

huangapple go评论101阅读模式
英文:

How to set up Spring Boot to make component metered without adding @Timed to each class, but rather specifying already used annotations like @Service

问题

我有一个充满了端点(即@Controller)和带有@Repository后置的@Service的Spring Boot应用程序。我想要将它们全部导出为定时指标到Micrometer。在某些时候,我也想要将它们全部禁用。在某个点上,我需要对所有带有@Service标签的类的方法进行计量,或者对@Repository的计时进行计量。因此,我不希望所有已经带有@Service注解的类都插入@Timed,然后再将其删除,我不知道如何在Spring Data仓库的接口中实现这一点。

为了使MeterRegistry考虑到所有带有@RestController标签的代码已经具有@Timed注解,从而使这个配置成为一个易于开启和关闭的属性,我应该设置哪种类型的bean呢?我知道,对于传入的http请求,management.metrics.web.server.request.autotime.enabled=true将对获取传入的http请求的时间产生影响,这对我很有用。

然而,如果可能的话,我想将相同的技巧应用到服务和存储库层。但是没有办法区分实际上是哪个服务,而不是@Service注解。因此,由于我不想在那里明确添加@Timed,有什么样的设置可以让MeterRegistry考虑到@Service标记类中的任何方法,并且在应用程序中的任何Spring Data存储库中的任何方法呢?

英文:

I have a Spring Boot application, full of endpoints (i.e. @Controller's) and @Service's with @Repository's behind them. I'd like to make all of them to export the timed metrics to Micrometer. At some point I'd like to disable them all too. At some point I would need to meter, for instance, all methods of @Service labelled classes or meter the timing of @Repository's. So I don't like all the classes that already keep @Service annotation to have @Timed inserted and the removed, and I have to idea how to do it with the Spring Data interfaces for repositories.

What kind of beans I should set up to make MeterRegistry consider that all the @RestController labeled code already have @Timed annotation, to make this configuration an easy to switch on and switch off property? I know, that for the incoming http request management.metrics.web.server.request.autotime.enabled=true will make this trick for getting the time of incoming http request, that will work for me.

However, the same probably I'd like to apply to service and repository layer, if possible. But there is no way to identify what is actually service, rather than @Service annotation. So as I don't like to add @Timed there explicitly, what kind of set up can be done to make MeterRegistry consider any method in @Service labelled class and in any Spring Data repository at the application?

答案1

得分: 3

没有现成的解决方案,但您可以自己实现,例如使用 Spring AOP。

您可以查看 TimedAspect 的源代码,特别是 @Around 方面,用于 @Timed 注解,并为 @Service@Repository 重新创建类似的实现。

英文:

There is no out-of-the-box solution for it, but you can implement it by yourself, eg., with Spring AOP.

You can look at the TimedAspect source code, especially at @Around aspect for @Timed annotation, and recreate it for @Service or @Repository.

huangapple
  • 本文由 发表于 2020年10月26日 19:49:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64536563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定