Moments — 時間流逝事件API

spring-modulith-moments 是一個時間流逝事件實現,其靈感主要來自於 Matthias Verraes 的部落格文章。它是一種基於事件的方法,用於觸發與特定時間段過去相關的操作。

要使用此抽象,請在專案中包含以下依賴:

  • Maven

  • Gradle

<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-moments</artifactId>
</dependency>
dependencies {
  implementation 'org.springframework.modulith:spring-modulith-moments'
}

新增到專案類路徑中的此依賴項會在您的應用中實現以下功能:

  • 應用程式碼可以在 Spring 事件監聽器中引用 HourHasPassed, DayHasPassed, WeekHasPassed, MonthHasPassed, QuarterHasPassed, YearHasPassed 等型別,以便在經過特定時間後收到通知。

  • 一個 org.springframework.modulith.Moments 型別的 Bean 可在 ApplicationContext 中使用,其中包含觸發這些事件的邏輯。

  • 如果 spring.modulith.moments.enable-time-machine 設定為 true,則該例項將是 org.springframework.modulith.TimeMachine 型別,它允許“時間轉移”,並由此觸發所有中間事件,這對於整合測試由時間流逝事件觸發的功能非常有用。

預設情況下,Moments 使用 Clock.systemUTC() 例項。要自定義此設定,請宣告一個 Clock 型別的 bean。

  • Java

  • Kotlin

@Configuration
class MyConfiguration {

  @Bean
  Clock myCustomClock() {
    // Create a custom Clock here
  }
}
@Configuration
class MyConfiguration {

  @Bean
  fun myCustomClock(): Clock {
    // Create a custom Clock here
  }
}

Moments 暴露以下應用屬性以進行高階定製:

表 1. 可用的應用屬性
屬性 預設值 描述

spring.modulith.moments.enable-time-machine

false

如果設定為 trueMoments 例項將是一個 TimeMachine,它暴露 API 以向前轉移時間。對於期望時間流逝事件觸發功能的整合測試很有用。

spring.modulith.moments.granularity

hours

觸發事件的最小粒度。備用值 days 可避免每小時事件。

spring.modulith.moments.locale

Locale.getDefault()

確定周邊界時使用的 Locale

spring.modulith.moments.quarter-start-month

Months.JANUARY

季度開始的月份。

spring.modulith.moments.zone-id

ZoneOffset#UTC

確定附加到已釋出事件的時間時使用的 ZoneId