4.6. MicroProfile 指标开发
4.6.1. 创建 MicroProfile 指标应用
创建一个应用,它将向应用发出的请求数返回。
流程
创建包含以下内容的类文件
HelloService.java
:package com.example.microprofile.metrics; public class HelloService { String createHelloMessage(String name){ return "Hello" + name; } }
创建包含以下内容的类文件
HelloWorld.java
:package com.example.microprofile.metrics; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import org.eclipse.microprofile.metrics.annotation.Counted; @Path("/") public class HelloWorld { @Inject HelloService helloService; @GET @Path("/json") @Produces({ "application/json" }) @Counted(name = "requestCount", absolute = true, description = "Number of times the getHelloWorldJSON was requested") public String getHelloWorldJSON() { return "{\"result\":\"" + helloService.createHelloMessage("World") + "\"}"; } }
更新
pom.xml
文件,使其包含以下依赖项:<dependency> <groupId>org.eclipse.microprofile.metrics</groupId> <artifactId>microprofile-metrics-api</artifactId> <scope>provided</scope> </dependency>
使用以下 Maven 命令构建应用程序:
$ mvn clean install wildfly:deploy
测试指标:
在 CLI 中运行以下命令:
$ curl -v http://localhost:9990/metrics | grep request_count | grep helloworld-rs-metrics
预期输出:
jboss_undertow_request_count_total{deployment="helloworld-rs-metrics.war",servlet="org.jboss.as.quickstarts.rshelloworld.JAXActivator",subdeployment="helloworld-rs-metrics.war",microprofile_scope="vendor"} 0.0
- 在浏览器中,导航到 URL http://localhost:8080/helloworld-rs/rest/json
在 CLI 中重新执行以下命令:
$ curl -v http://localhost:9990/metrics | grep request_count | grep helloworld-rs-metrics
预期输出:
jboss_undertow_request_count_total{deployment="helloworld-rs-metrics.war",servlet="org.jboss.as.quickstarts.rshelloworld.JAXActivator",subdeployment="helloworld-rs-metrics.war",microprofile_scope="vendor"} 1.0