扩展DataSourcePublicMetrics以获取其他指标

时间:2022-07-27 18:19:07

We are using a custom DataSource which achieves multi-tenancy. (We have a single DataSource bean which acts like a proxy to other datasources, and the tenant context is set using ThreadLocal variables. My requirement is to get the metrics of the individual datasources proxied by that single DataSource Bean.) Basically, i need to somehow add additional metrics. It seems like the best way would be to extend DataSourcePublicMetrics, since PublicMetricsAutoConfiguration conditionally creates this bean. The problem is that the fields in DataSourcePublicMetrics are all private making reuse difficult. The only solution i see is hide all the internal variables and override the public methods. Is there a better way? I'm using spring-boot 1.2.2.RELEASE.

我们正在使用自定义DataSource来实现多租户。 (我们有一个DataSource bean,它就像其他数据源的代理一样,租户上下文是使用ThreadLocal变量设置的。我的要求是获取由单个DataSource Bean代理的各个数据源的度量。)基本上,我需要以某种方式添加其他指标。似乎最好的方法是扩展DataSourcePublicMetrics,因为PublicMetricsAutoConfiguration有条件地创建了这个bean。问题是DataSourcePublicMetrics中的字段都是私有的,使得重用变得困难。我看到的唯一解决方案是隐藏所有内部变量并覆盖公共方法。有没有更好的办法?我正在使用spring-boot 1.2.2.RELEASE。

1 个解决方案

#1


Use composition instead of inheritance.

使用组合而不是继承。

MyCustomMetrics implements PublicMetrics

Any bean the implements PublicMetrics is picked up by the actuator to be exposed at /metrics. DataSourcePublicMetrics implements this interface.

实现PublicMetrics的任何bean都被执行器拾取,以暴露在/ metrics中。 DataSourcePublicMetrics实现此接口。

You then inject the DataSourcePublicMetrics bean into MyCustomMetrics (this could even be your custom DataSource, but probably better to create a different class). Implement the contract of PublicMetrics.

然后,将DataSourcePublicMetrics bean注入MyCustomMetrics(这甚至可能是您的自定义DataSource,但最好创建一个不同的类)。实施PublicMetrics的合同。

public Collection<Metric<?>> metrics()

Just defer it to the DataSourcePublicMetrics implementation, and also add whatever custom metrics you want.

只需将其推迟到DataSourcePublicMetrics实现,并添加您想要的任何自定义指标。

#1


Use composition instead of inheritance.

使用组合而不是继承。

MyCustomMetrics implements PublicMetrics

Any bean the implements PublicMetrics is picked up by the actuator to be exposed at /metrics. DataSourcePublicMetrics implements this interface.

实现PublicMetrics的任何bean都被执行器拾取,以暴露在/ metrics中。 DataSourcePublicMetrics实现此接口。

You then inject the DataSourcePublicMetrics bean into MyCustomMetrics (this could even be your custom DataSource, but probably better to create a different class). Implement the contract of PublicMetrics.

然后,将DataSourcePublicMetrics bean注入MyCustomMetrics(这甚至可能是您的自定义DataSource,但最好创建一个不同的类)。实施PublicMetrics的合同。

public Collection<Metric<?>> metrics()

Just defer it to the DataSourcePublicMetrics implementation, and also add whatever custom metrics you want.

只需将其推迟到DataSourcePublicMetrics实现,并添加您想要的任何自定义指标。