下面列出了怎么用com.codahale.metrics.health.HealthCheckRegistry的API类实例代码及写法,或者点击链接到github查看源代码。
private JbootMetricManager() {
if (!metricsConfig.isConfigOk()) {
return;
}
metricRegistry = new MetricRegistry();
healthCheckRegistry = new HealthCheckRegistry();
List<JbootMetricReporter> reporters = getReporters();
if (ArrayUtil.isNullOrEmpty(reporters)) {
return;
}
for (JbootMetricReporter reporter : reporters) {
try {
reporter.report(metricRegistry);
} catch (Throwable ex) {
LOG.error(ex.toString(), ex);
}
}
this.enable = true;
}
public static HikariDataSource getDataSourceFromConfig(
Config conf
, MetricRegistry metricRegistry
, HealthCheckRegistry healthCheckRegistry) {
HikariConfig jdbcConfig = new HikariConfig();
jdbcConfig.setPoolName(conf.getString("poolName"));
jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
jdbcConfig.setUsername(conf.getString("username"));
jdbcConfig.setPassword(conf.getString("password"));
jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));
// Add HealthCheck
jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);
// Add Metrics
jdbcConfig.setMetricRegistry(metricRegistry);
return new HikariDataSource(jdbcConfig);
}
public static HikariDataSource getDataSourceFromConfig(
Config conf
, MetricRegistry metricRegistry
, HealthCheckRegistry healthCheckRegistry) {
HikariConfig jdbcConfig = new HikariConfig();
jdbcConfig.setPoolName(conf.getString("poolName"));
jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
jdbcConfig.setUsername(conf.getString("username"));
jdbcConfig.setPassword(conf.getString("password"));
jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));
// Add HealthCheck
jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);
// Add Metrics
jdbcConfig.setMetricRegistry(metricRegistry);
return new HikariDataSource(jdbcConfig);
}
public static void main(String[] args) {
SpringApplication.run(MonetaSpringBootApplication.class, args);
// Find and read application configuration
MonetaConfiguration config = new MonetaConfiguration();
// Install all health checks
HealthCheckRegistry registry = new HealthCheckRegistry();
for (String checkName : MonetaEnvironment.getConfiguration()
.getHealthChecks()
.keySet()) {
registry.register(checkName, MonetaEnvironment.getConfiguration()
.getHealthChecks()
.get(checkName));
}
ActuatorHealthIndicator.setHealthCheckRegistry(registry);
// Install metrics and JMX
MetricRegistry metricRegistry = new MetricRegistry();
final JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry)
.build();
jmxReporter.start();
}
private ServletContextHandler getMetricsHandler() {
MetricRegistry registry = Metrics.getRegistry();
HealthCheckRegistry healthCheckRegistry = Metrics.getHealthCheckRegistry();
healthCheckRegistry.register("rotation", new Rotation(configuration.getRotationStatusFilePath()));
registry.registerAll(new GarbageCollectorMetricSet());
registry.registerAll(new MemoryUsageGaugeSet());
registry.registerAll(new ThreadStatesGaugeSet());
registry.registerAll(new JvmAttributeGaugeSet());
ServletContextHandler servletContextHandler = new ServletContextHandler();
servletContextHandler.setContextPath("/__metrics");
servletContextHandler.setAttribute(MetricsServlet.class.getCanonicalName() + ".registry", registry);
servletContextHandler.setAttribute(HealthCheckServlet.class.getCanonicalName() + ".registry", healthCheckRegistry);
servletContextHandler.addServlet(new ServletHolder(new AdminServlet()), "/*");
return servletContextHandler;
}
@Test
public void testAllHealthy() {
final HealthCheckRegistry registry = new HealthCheckRegistry();
registry.register("pass1", stubHealthCheck(HealthCheck.Result.healthy()));
registry.register("pass2", stubHealthCheck(HealthCheck.Result.healthy()));
final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
assertThat(gauge.getValue(), is(1));
}
/**
* Initializes health checks.
*
* @param injector
*/
private void initHealthChecks(Injector injector) {
LOGGER.info("Initializing HealthChecks");
healthCheckRegistry = new HealthCheckRegistry();
healthCheckRegistry.register(MesosMasterHealthCheck.NAME, injector.getInstance(MesosMasterHealthCheck.class));
healthCheckRegistry.register(ZookeeperHealthCheck.NAME, injector.getInstance(ZookeeperHealthCheck.class));
healthCheckRegistry.register(MesosDriverHealthCheck.NAME, injector.getInstance(MesosDriverHealthCheck.class));
}
@Produces
@Named("not_registered_healthcheck")
HealthCheck anInjectedCheck(HealthCheckRegistry registry, InjectionPoint ip) {
HealthCheck check3 = new HealthCheck() {
@Override
protected Result check() {
return Result.healthy("check3");
}
};
registry.register("check3", check3);
return check3;
}
/***
* Initializes the health check registry
*
* @return health check registry bean
*/
@Bean
public HealthCheckRegistry healthCheckRegistry(ApplicationContext context) {
final HealthCheckRegistry bean = new HealthCheckRegistry();
// auto-register beans implementing health checks
Map<String,HealthCheck> healthChecks = context.getBeansOfType(HealthCheck.class);
for (HealthCheck check : healthChecks.values()) {
bean.register( check.getClass().getName(), check );
}
return bean;
}
@Override
public void run() {
StormClusterState clusterState = workerData.getZkCluster();
String topologyId = workerData.getTopologyId();
Map<Integer, HealthCheckRegistry> taskHealthCheckMap = JStormHealthCheck.getTaskhealthcheckmap();
int cnt = 0;
for (Map.Entry<Integer, HealthCheckRegistry> entry : taskHealthCheckMap.entrySet()) {
Integer taskId = entry.getKey();
Map<String, Result> results = entry.getValue().runHealthChecks();
for (Map.Entry<String, Result> result : results.entrySet()) {
if (!result.getValue().isHealthy()) {
try {
clusterState.report_task_error(topologyId, taskId, result.getValue().getMessage(),
ErrorConstants.WARN, ErrorConstants.CODE_QUEUE_FULL, ErrorConstants.DURATION_SECS_QUEUE_FULL);
cnt++;
} catch (Exception e) {
LOG.error("Failed to update health data in ZK for topo-{} task-{}.", topologyId, taskId, e);
}
}
}
}
if (cnt > 0) {
LOG.info("Successfully updated {} health data to ZK for topology:{}", cnt, topologyId);
}
}
private Server(XConfig config, int port) {
this.config = config;
this.port = port >= 0 ? port : config.port();
this.sslContext = config.sslContext();
this.healthCheckRegistry = new HealthCheckRegistry(config.asyncHealthCheckThreadCount());
// This adds support for normal constructor binding.
// See: https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names
ObjectMapper mapper =
new ObjectMapper().registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
// Json encoder for Proto
JsonFormat.Printer printer = JsonFormat.printer().omittingInsignificantWhitespace();
// Default instances for protobuf generated classes.
ProtoDefaultInstances protoDefaultInstances = new ProtoDefaultInstances();
this.contextBuilder =
ServerContext.builder()
.requestMeter(metricRegistry.meter("requests"))
.encoders(
Encoders.builder()
.defaultContentType(config.defaultContentType())
.encoder(new JsonEncoder(mapper, printer))
// TODO (AD): For now we won't support text/plain encoding.
// Leaving this here as a placeholder.
// .encoder(new TextEncoder())
.encoder(new ProtoEncoder())
.build())
.decoders(
Decoders.builder()
.defaultContentType(config.defaultContentType())
.decoder(new JsonDecoder(mapper, protoDefaultInstances))
.decoder(new ProtoDecoder(protoDefaultInstances))
.build())
.exceptionHandler(ResponseFactory::exception);
addResponseCodeMeters(contextBuilder, metricRegistry);
}
public static void unregisterTaskHealthCheck(int taskId, String name) {
HealthCheckRegistry healthCheckRegister = taskHealthCheckMap.get(taskId);
if (healthCheckRegister != null) {
healthCheckRegister.unregister(name);
}
}
@Test
public void test() throws SQLException {
Config config = ConfigFactory.empty()
.withValue("poolName", ConfigValueFactory.fromAnyRef("test pool"))
.withValue("jdbcUrl", ConfigValueFactory.fromAnyRef("jdbc:hsqldb:mem:testdb"))
.withValue("maximumPoolSize", ConfigValueFactory.fromAnyRef(10))
.withValue("minimumIdle", ConfigValueFactory.fromAnyRef(2))
.withValue("username", ConfigValueFactory.fromAnyRef("SA"))
.withValue("password", ConfigValueFactory.fromAnyRef(""))
.withValue("cachePrepStmts", ConfigValueFactory.fromAnyRef(true))
.withValue("prepStmtCacheSize", ConfigValueFactory.fromAnyRef(256))
.withValue("prepStmtCacheSqlLimit", ConfigValueFactory.fromAnyRef(2048))
.withValue("useServerPrepStmts", ConfigValueFactory.fromAnyRef(true))
;
MetricRegistry metricRegistry = new MetricRegistry();
HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
try (HikariDataSource ds = ConnectionPool.getDataSourceFromConfig(config, metricRegistry, healthCheckRegistry)) {
assertTrue(ds.getPoolName().equals("test pool"));
assertTrue(ds.getMaximumPoolSize() == 10);
assertTrue(ds.getMinimumIdle() == 2);
assertTrue(ds.getUsername().equals("SA"));
assertTrue(ds.getPassword().equals(""));
Properties dsp = ds.getDataSourceProperties();
assertTrue(((boolean)dsp.get("cachePrepStmts")) == true);
assertTrue(((int)dsp.get("prepStmtCacheSize")) == 256);
assertTrue(((int)dsp.get("prepStmtCacheSqlLimit")) == 2048);
assertTrue(((boolean)dsp.get("useServerPrepStmts")) == true);
// Using identity equals on purpose
assertTrue(ds.getHealthCheckRegistry() == healthCheckRegistry);
assertTrue(ds.getMetricRegistry() == metricRegistry);
try (Connection conn = ds.getConnection()) {
assertTrue(conn.isValid(1000));
}
}
}
@Before
public void addHealthCheck() {
HealthCheckRegistry registry = CDI.current().select(HealthCheckRegistry.class).get();
registry.register("hammock", new HealthCheck() {
@Override
protected Result check() throws Exception {
return Result.healthy("Hammock is online");
}
});
}
public ServletReporter(MetricRegistry metricRegistry,
HealthCheckRegistry healthCheckRegistry,
int port) {
this.metricRegistry = metricRegistry;
this.healthCheckRegistry = healthCheckRegistry;
this.port = port;
this.jettyServer = new Server(port);
}
@Test
public void testOneFails() {
final HealthCheckRegistry registry = new HealthCheckRegistry();
registry.register("pass1", stubHealthCheck(HealthCheck.Result.healthy()));
registry.register("fail1", stubHealthCheck(HealthCheck.Result.unhealthy("error")));
final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
assertThat(gauge.getValue(), is(0));
}
@Test
public void testAllFail() {
final HealthCheckRegistry registry = new HealthCheckRegistry();
registry.register("fail1", stubHealthCheck(HealthCheck.Result.unhealthy("error")));
registry.register("fail2", stubHealthCheck(HealthCheck.Result.unhealthy("error")));
final TotalHealthCheckGauge gauge = new TotalHealthCheckGauge(registry);
assertThat(gauge.getValue(), is(0));
}
public ServletReporter(MetricRegistry metricRegistry,
HealthCheckRegistry healthCheckRegistry,
int port) {
this.metricRegistry = metricRegistry;
this.healthCheckRegistry = healthCheckRegistry;
this.port = port;
this.jettyServer = new Server(port);
}
@Before
public void setUp() throws Exception {
this.registry = mock(HealthCheckRegistry.class);
this.environment = mock(Environment.class);
this.keywhizConfig = mock(KeywhizConfig.class);
when(environment.healthChecks()).thenReturn(registry);
when(keywhizConfig.getStatusCacheExpiry()).thenReturn(Duration.ofSeconds(1));
this.status = new StatusResource(keywhizConfig, environment);
}
@Override
public boolean shouldBeInDiscovery(HealthCheckRegistry registry)
{
return Iterables.all(registry.runHealthChecks().values(), new Predicate<HealthCheck.Result>()
{
@Override
public boolean apply(HealthCheck.Result result)
{
return result.isHealthy();
}
});
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
public HealthCheckRegistry getHealthCheckRegistry() {
assert healthCheckRegistry != null;
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
public HealthServlet(HealthCheckRegistry healthCheckRegistry) {
this.healthCheckRegistry = healthCheckRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}