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 事件監聽器中參考 HourHasPassedDayHasPassedWeekHasPassedMonthHasPassedQuarterHasPassedYearHasPassed 類型,以便在特定時間量經過時收到通知。

  • 類型為 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

如果設定為 true,則 Moments 實例將會是 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