我正在创建一个Dropwizard软件包,可在我的所有微服务中重复使用。我想标准化的一件事是每个服务使用的MetricRegistry
。
如果我可以通过简单地在init上添加我的捆绑包就可以将每个服务配置为使用相同的MetricRegistry
,那将是非常棒的,就像这样:
class Microservice1 extends Application<Microservice1Config> {
@Override
void initialize(Bootstrap<Microservice1Config> cfg) {
// Boom! Standardized metrics/reporters configured and initialized!
bootstrap.addBundle(new MyBundle())
}
}
问题是Bundle
API似乎不利于这种行为:
class MyBundle implements Bundle {
MetricRegistry metricRegistry
@Override
void initialize(Bootstrap bootstrap) {
}
@Override
void run(Environment environment) {
environment.jersey().register(???)
}
}
由于register(...)
方法未将metricRegistry
注册为JAX-RS资源,所以我对如何进行连接一无所知,以便将此metricRegistry
用于整个微服务的所有指标。想法?
我正在寻找的是放置以下内容的位置:
MetricRegistry metricRegistry = new MetricRegistry()
Slf4jReporter slf4jReporter = Slf4jReporter.forRegistry(metricRegistry)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.SECONDS)
.build()
slf4jReporter.start(5, TimeUnit.SECONDS)
嗯,有一个可从environment.metrics()
访问的度量标准注册表。有很多方法可以将其注入您需要的地方。我使用dropwizard-guice捆绑包添加Guice支持。
private GuiceBundle<MyConfiguration> guiceBundle;
@Override
public void initialize(Bootstrap<MyConfiguration> bootstrap) {
guiceBundle = GuiceBundle.<MyConfiguration>newBuilder()
.addModule(new MyModule())
.setConfigClass(MyConfiguration.class)
.build(Stage.DEVELOPMENT);
bootstrap.addBundle(guiceBundle);
}
然后,我在应用程序的模块中为度量标准注册表创建提供者规则。
public class MyModule extends AbstractModule {
...
@Provides
@Singleton
public MetricRegistry provideRegistry( Environment environment ) {
return environment.metrics();
}
}
并且在我的资源中,我将注册表标记为已注入。
@Path("/resource")
public class MyResource {
@Inject
MetricRegistry registry;
}
最后,我从Guice的注入器请求我的静态资源,然后将一个实例而不是类名传递给Jersey。
@Override
public void run(Environment environment) {
Injector injector = guiceBundle.getInjector();
environment.jersey().register(injector.getInstance(MyResource.class));
}
[您可能只注册了类名,并依靠Guice / HK2桥来提供注入,但是从历史上看,Guice / HK2的集成一直是个问题。
一旦连接了度量标准注册表,您将需要配置度量以将数据发送到某处。您可以使用metrics configuration block执行此操作。
例如,如果您希望将指标发送给石墨,则可以设置graphite metrics reporter。您将需要添加对石墨报告器的依赖性。
<dependency>
<artifactId>dropwizard-metrics-graphite</artifactId>
<groupId>io.dropwizard</groupId>
<version>${dropwizard.version}</version>
</dependency>
并添加报告程序的配置。
metrics:
reporters:
- type: graphite
prefix: <PREFIX_FOR_METRICS>
host: <GRAPHITE_HOST>
port: <GRAPHITE_PORT>
frequency: 10s