4.6. MicroProfile Metrics の開発

4.6.1. MicroProfile Metrics アプリケーションの作成

アプリケーションに対して行われるリクエスト数を返すアプリケーションを作成します。

手順

  1. 以下の内容を含むクラスファイル HelloService.java を作成します。

    package com.example.microprofile.metrics;
    
    public class HelloService {
        String createHelloMessage(String name){
            return "Hello" + name;
        }
    }
  2. 以下の内容を含むクラスファイル 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") + "\"}";
        }
    }
  3. 以下の依存関係を含めるように pom.xml ファイルを更新します。

    <dependency>
        <groupId>org.eclipse.microprofile.metrics</groupId>
        <artifactId>microprofile-metrics-api</artifactId>
        <scope>provided</scope>
    </dependency>
  4. 以下の Maven コマンドを使用してアプリケーションをビルドします。

    $ mvn clean install wildfly:deploy
  5. メトリックをテストします。

    1. 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
    2. ブラウザーで http://localhost:8080/helloworld-rs/rest/json にアクセスします。
    3. 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