在我的應用程式中,我使用的是 spring webflux,并且我正在使用 webclient 從某些 3rd 方 API 中檢索詳細資訊。現在,我想將第一次 webClient 回應存盤在記憶體快取中,以便第二次可以直接從快取中獲取這些回應。我正在嘗試在記憶體快取機制和“咖啡因”中使用 Spring Boot。但沒有一個按預期作業。 應用程式.yml:
spring:
cache:
cache-names: employee
caffiene:
spec: maximumSize=200, expireAfterAccess=5m
EmployeeApplication.java:
@SpringBootApplication
@EnableCaching
public class EmployeeApplication{
public static void main(String[] args){
}
}
EmployeeController.java:employee/all它有一個從第 3 方 API 獲取所有員工
的休息端點。員工服務.java:
@Service
@Slf4j
public class EmployeeService{
@Autowired
private WebClient webClient;
@Autowired
private CacheManager cacheManager;
@Cacheable("employee")
public Mono<List<Employee>> getAllEmployee(){
log.info("inside employee service {}");
return webClient.get()
.uri("/employees/")
.retrieve()
.bodyToMono(Employee.class);
}
}
雖然我已經配置了快取名稱,但當我第二次點擊 url 時,它正在呼叫服務方法。需要使用什么快取機制來快取 Mono 回應?請建議。
uj5u.com熱心網友回復:
有幾個選項可以快取回應式發布者。
- 使用回應式
cacheAPI 快取Mono定義的持續時間
employeeService.getAllEmployee()
.cache(Duration.ofMinutes(60))
.flatMap(employees -> {
// process data
})
- 將外部快取(番石榴、咖啡因)與
CacheMonofrom一起使用reactor-extra。如果您需要根據不同的輸入快取結果(例如多租戶環境),此選項更適合
這是 Guava 的示例,但您可以對其進行調整CacheManager
Cache<String, List<Employee>> cache = CacheBuilder.newBuilder()
.expireAfterWrite(cacheTtl)
.build();
Mono<List<Employee>> getEmployee(String tenant) {
return CacheMono.lookup(key -> Mono.justOrEmpty(cache.getIfPresent(key)).map(Signal::next), tenant)
.onCacheMissResume(() -> employeeService.getAllEmployee(tenant))
.andWriteWith((key, signal) -> Mono.fromRunnable(() ->
Optional.ofNullable(signal.get())
.ifPresent(value -> cache.put(key, value))
)
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/446015.html
標籤:春天 弹簧靴 缓存 spring-webflux
