我需要以不同的时间间隔检查一些端点,所以我设置了 Caffeine 的缓存构建器。
this.localeWeatherCache = newBuilder().build();
this.currentWeatherCache=newBuilder().expireAfterWrite(Duration.ofHours(3)).build();
this.weatherForecastsCache = newBuilder().expireAfterWrite(Duration.ofHours(12)).build();
在我的服务中,我调用这 3 个端点,最后我使用 Mono.zip() 返回包含所有详细信息的对象。
在我的测试中,我注意到climaTempoRepository.findLocaleByCityNameAndState 执行了两次,并且在currentWeather缓存过期后,它再次调用locale端点,weatherForecast 也是如此,它再次调用locale。
为什么会失败?它不应该使用缓存吗?还是我的做法不对?
非常感谢任何帮助或指示!:)
public Mono<Weather> weatherForecastByLocation(Location location) {
Mono<ClimaTempoLocale> locale =
CacheMono.lookup(key ->
Mono.justOrEmpty(localeWeatherCache.getIfPresent(key))
.map(Signal::next), location)
.onCacheMissResume(() -> climaTempoRepository.findLocaleByCityNameAndState(location.city(), location.state()))
.andWriteWith((key, signal) -> Mono.fromRunnable(() ->
Optional.ofNullable(signal.get())
.ifPresent(value -> localeWeatherCache.put(key, value))));
Mono<CurrentWeather> currentWeather =
CacheMono.lookup(key ->
Mono.justOrEmpty(currentWeatherCache.getIfPresent(key))
.map(Signal::next), location)
.onCacheMissResume(() -> locale.flatMap(climaTempoRepository::findCurrentWeatherByLocale)
.subscribeOn(Schedulers.elastic()))
.andWriteWith((key, signal) -> Mono.fromRunnable(() ->
Optional.ofNullable(signal.get())
.ifPresent(value -> currentWeatherCache.put(key, value))));
Mono<WeatherForecasts> weatherForecasts =
CacheMono.lookup(key ->
Mono.justOrEmpty(weatherForecastsCache.getIfPresent(key))
.map(Signal::next), location)
.onCacheMissResume(() -> locale.flatMap(climaTempoRepository::findDailyForecastByLocale)
.subscribeOn(Schedulers.elastic()))
.andWriteWith((key, signal) -> Mono.fromRunnable(() ->
Optional.ofNullable(signal.get())
.ifPresent(value -> weatherForecastsCache.put(key, value))));
return Mono.zip(currentWeather,
weatherForecasts,
(current, forecasts) ->
Weather.buildWith(builder -> {
builder.location = location;
builder.currentWeather = current;
builder.weatherForecasts = forecasts;
}));
}