实现说明
活动部件是类 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());
}
}