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