0

我使用Apache中的HttpClient的CachingHttpClient實現。和具有以下情形:Apache HttpClient在條件請求中返回緩存正文

我提出爲返回了首標的響應的資源的請求: 緩存控制:最大年齡= 5。 因此CachingHttpClient緩存響應。

我以下我正在使用If-Modified-Since對同一資源進行有條件的請求。我得到一個狀態代碼304的響應沒有修改(順便說一句,它甚至不檢查服務器)。沒有答覆機構。這很好,但我想訪問緩存體,因爲如果它沒有更新,我想使用它。

的問題是:

是否有訪問第一次調用緩存響應的便捷方式?

(使用org.apache.httpcomponents:HttpClient的,org.apache.httpcomponents:HttpClient的高速緩衝存儲器;版本4.5.2)

服務器側:

@RequestMapping("/number") 
     public int getNumber(HttpServletResponse response, HttpServletRequest request) { 
      log.info("Number gen called"); 
      response.setHeader("Cache-Control", "max-age=" + 5); 
      return random.nextInt(); 
     } 

客戶端:

HttpGet httpget = new HttpGet("http://localhost:8080/number"); 

httpget.setHeader("If-Modified-Since", java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME. 
     format(ZonedDateTime.now(ZoneId.of("GMT")).minusSeconds(1))); 

HttpResponse resp = httpClient.execute(httpget); 
     log.info("code: " + resp.getStatusLine().getStatusCode()); 
     // here fails because no body on 2. call 
String responseString = new BasicResponseHandler().handleResponse(resp); 

HTTP客戶端初始化

@Bean 
    public HttpClient httpClient() { 
     return CachingHttpClients.createMemoryBound(); 
    } 

回答

0

好的,如果我明確配置緩存,我也可以直接使用該緩存對象,所以這是一個典型的RTFM問題,我的不好。

@Bean 
public HttpCacheStorage httpCacheStorage() { 
    CacheConfig cacheConfig = CacheConfig.custom() 
      .setMaxCacheEntries(1000) 
      .setMaxObjectSize(8192) 
      .build(); 
    HttpCacheStorage cacheStorage = new BasicHttpCacheStorage(cacheConfig); 
    return cacheStorage; 
}