-3
public class CacheDemo {

public static void main(String[] args) {
    CacheConfig cacheConfig = new CacheConfig();
    cacheConfig.setMaxCacheEntries(1000);
    cacheConfig.setMaxObjectSizeBytes(1024 * 1024);

    HttpClient cachingClient = new CachingHttpClient(new DefaultHttpClient(), cacheConfig);

    HttpContext localContext = new BasicHttpContext();

    sendRequest(cachingClient, localContext);
    CacheResponseStatus responseStatus = (CacheResponseStatus) localContext.getAttribute(
            CachingHttpClient.CACHE_RESPONSE_STATUS);
    checkResponse(responseStatus);


    sendRequest(cachingClient, localContext);
    responseStatus = (CacheResponseStatus) localContext.getAttribute(
            CachingHttpClient.CACHE_RESPONSE_STATUS);
    checkResponse(responseStatus);
}

static void sendRequest(HttpClient cachingClient, HttpContext localContext) {
    HttpGet httpget = new HttpGet("http://www.mydomain.com/content/");
    HttpResponse response = null;
    try {
        response = cachingClient.execute(httpget, localContext);
    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpEntity entity = response.getEntity();
    try {
        EntityUtils.consume(entity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

static void checkResponse(CacheResponseStatus responseStatus) {
    switch (responseStatus) {
        case CACHE_HIT:
            System.out.println("A response was generated from the cache with no requests "
                    + "sent upstream");
            break;
        case CACHE_MODULE_RESPONSE:
            System.out.println("The response was generated directly by the caching module");
            break;
        case CACHE_MISS:
            System.out.println("The response came from an upstream server");
            break;
        case VALIDATED:
            System.out.println("The response was generated from the cache after validating "
                    + "the entry with the origin server");
            break;
    }
}

}

它不适合我。

每次它从服务器获取数据,而不是从缓存中获取数据。

我正在使用 jar "httpclient-cache-4.1-beta1"

4

1 回答 1

0

你还没有向我们展示你的 HTTP 服务器发生了什么。mydomain.com/content 上的服务是否在 HTTP 响应上设置了正确的 Cache-Control 标头?要使缓存起作用,您需要让 HTTP 服务器或 Web 应用程序指示数据是否可以缓存,以及数据可以使用适当的标头缓存的长度。

此外,检查 CachingHttpClient 上记录的 API 以查看它期望来自 Web 服务器的标头。

于 2013-04-10T05:17:07.683 回答