1
0

More than 1 year has passed since last update.

SpringBootで個人的に便利だと思った記法

Posted at

はじめに

豊田高専 Advent Calendar 2021、19日目の記事になります。
SpringBootを触ってきて、個人的に便利だと思った記法をいくつか紹介しようかと思います。

時間の扱い方

SpringBootにおいて時間を扱う際はClockをBean定義しておくとテストが書きやすい。
テストを書く際はBefore, BeforeEachでテストしたい日付のInstantを定義し、getClockをモック化する。

ClockConfig.java
@Configuration
public class ClockConfig {
    @Bean
    public Clock getClock() {
        return Clock.system(ZoneId.of("Asia/Tokyo"));
    }
}
Sample.java
@Component
@RequiredArgsConstructor
public class Sample {
    private final ClockConfig clockConfig

    public void hoge() {
         Clock clock = clockConfig.getClock();
         LocalDateTime localDateTime = LocalDateTime.now(clock);
    }
}
SampleTest.java
@SpringBootTest(classes = Sample.class)
public class SampleTest {
    @Autowired
    Sample sample;

    @MockBean
    ClockConfig clockConfig;

    @BeforeEach
    public void beforeEach() {
        //clockの初期化
        Instant instant = Instant.parse("2021-01-01T09:45:32Z");
        doReturn(Clock.fixed(instant, ZoneId.of("Asia/Tokyo")).when(clockConfig).getClock();
    }
}

メトリクスの集め方

Micrometerを用いてExceptionの発生数などの任意のメトリクスを自由に取ることができます。
取得したメトリクスはPromethusで可視化することが可能です。

pom.xmlにモニタリングツールを追加します。

pom.xml
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>io.micrometer</groupId>
            <artifactId>micrometer-registry-prometheus</artifactId>
        </dependency>
    </dependencies>

任意のExceptionの発生数をカウントするClassを作成します。
Metrics.counterの引数はメトリクス名,タグ名,タグ詳細になります。
サンプルコードで取得可能なメトリクス形式は以下のようになります。

api_exception_count_total{exception="IOException",} 0.0
api_exception_count_total{exception="Exception",} 0.0
ExceptionCounter.java
@Component
public class ExceptionCounter {
    private final Counter ioException;
    private final Counter exception;

    public ExceptionCounter() {
        this.ioException = Metrics.counter("api.exception.count", "exception", "IOException");
        this.exception = Metrics.counter("api.exception.count", "exception", "Exception");
    }

    public void incrementIoException() {
        this.ioException.increment();
    }

    public void incrementException() {
        this.exception.increment();
    }
}

このClassを例外ハンドリングしているClassでインジェクションし、各Exceptionに合わせたincrementメソッドを実行すればMicrometerを用いた計測が可能です。

デフォルトではpromethusエンドポイントの一部しか公開されていないので、application.propertiesに以下を追加してエンドポイントを開放します。

application.properties
management.endpoints.web.exposure.include=prometheus

動作確認はhttp://localhost:8080/actuator/prometheusにアクセスすることで可能です。

さいごに

Junit5のParameterizedTestについてのおまけを書こうと思いましたが、時間がないので断念しました。
コメント等つけば書くかもです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0