1

我正在寻找类似以下的事情:

@HystrixCommand(fallbackMethod = "returnLastGoodCachedCopy")
void performRequest(String someArg) { 
    // Make HTTP request using RestTemplate configured with EHCache  
}

void returnLastGoodCachedCopy(String someArg) {
    // Return the last successful response 
}

对于更多背景知识,我正在使用 Spring Boot,并设置RestTemplate类似的东西以使用 EHCache:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(clientHttpRequestFactory());
}

@Bean
public CloseableHttpClient httpClient() {
    CacheConfig cacheConfig = CacheConfig.custom()
            .setMaxCacheEntries(this.httpClientProperties.getMaxCacheEntries())
            .setMaxObjectSize(this.httpClientProperties.getMaxObjectSize())
            .setHeuristicCachingEnabled(this.httpClientProperties.getHeuristicLifetimeEnabled())
            .setHeuristicDefaultLifetime(this.httpClientProperties.getHeuristicLifetimeSeconds()).build();

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(this.httpClientProperties.getConnectTimeout())
            .setSocketTimeout(this.httpClientProperties.getSocketTimeout()).build();

    Ehcache httpEhcache = (Ehcache) this.ehCacheManager.getCache(httpClientProperties.getCacheName())
            .getNativeCache();

    EhcacheHttpCacheStorage ehcacheHttpCacheStorage = new EhcacheHttpCacheStorage(httpEhcache);

    CloseableHttpClient cachingClient = CachingHttpClients.custom().setCacheConfig(cacheConfig)
            .setHttpCacheStorage(ehcacheHttpCacheStorage).setDefaultRequestConfig(requestConfig).build();

    return cachingClient;
}

private ClientHttpRequestFactory clientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
    return factory;
}

所以我的一个想法是使用相同的请求 EHCache,但考虑到缓存基于缓存控制标头,我不确定这是一个合适的解决方案,我想将其分开,因此我可以返回一个有效的响应不管是否过期。

我的另一个想法是配置一个单独的 EHCache 缓存,并自己存储响应,然后考虑到我设置了键和值的格式,我可以更轻松地访问它们。

在我走这条路之前,我想看看 Hystrix 中是否已经有任何东西可以处理这种情况,或者是否有任何其他推荐的方法。

4

0 回答 0