← 中文资源

简体中文版本

InstantSource 固定、偏移与整点步进时间源

在只需 UTC 瞬时值的逻辑中注入 JDK 17 InstantSource 替代 Clock,组合 fixed、offset 与 tick 封装并按需转时区时钟。

阅读英文原文

实现说明

活动部件是类 TokenExpiryClock和函数 isExpired、main。

使用要点

  • 省去了安装依赖工作:源码调取到的全部 API 全部随平台提供。
  • 跑完文件,输出里会留下标记——fixed instant:、expired at T+0:、shifted T+5m:。
  • 运行整个文件:main 会依次驱动 isExpired。

常见问题

运行「InstantSource 固定、偏移与整点步进时间源」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 fixed instant:、expired at T+0:、shifted T+5m: 标签标明各步骤。

签名一览:static boolean isExpired(InstantSource source, Instant expiresAt)

核心语句

return !source.instant().isBefore(expiresAt);

代码示例

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.InstantSource;
import java.time.ZoneOffset;

public class TokenExpiryClock {

    static boolean isExpired(InstantSource source, Instant expiresAt) {
        return !source.instant().isBefore(expiresAt);
    }

    public static void main(String[] args) {
        Instant issuedAt = Instant.parse("2026-11-24T08:00:17Z");
        Instant expiresAt = Instant.parse("2026-11-24T08:05:00Z");

        // InstantSource drops ZoneId when domain logic works purely with UTC instants
        InstantSource fixed = InstantSource.fixed(issuedAt);
        System.out.println("fixed instant:  " + fixed.instant() + " millis=" + fixed.millis());
        System.out.println("expired at T+0: " + isExpired(fixed, expiresAt));

        // offset() shifts any base source by a fixed duration for deterministic tests
        InstantSource shifted = InstantSource.offset(fixed, Duration.ofMinutes(5));
        System.out.println("shifted T+5m:   " + shifted.instant() + " expired=" + isExpired(shifted, expiresAt));

        // tick() truncates readings to whole 10-second buckets for stable window keys
        InstantSource bucketed = InstantSource.tick(fixed, Duration.ofSeconds(10));
        System.out.println("10s tick read:  " + bucketed.instant());

        // Bridge to Clock only at edges that format calendar fields in a ZoneId
        Clock utcClock = fixed.withZone(ZoneOffset.UTC);
        System.out.println("bridged zone:   " + utcClock.getZone() + " -> " + utcClock.instant());
    }
}