繁体   English   中英

有一种简单的方法可以手动强制缓存HttpClient 4.3.x绕过缓存吗?

[英]Is there an easy way to manually force a caching HttpClient 4.3.x to bypass the cache?

我正在使用CachingHttpClientBuilder通过HttpServlet创建一个CloseableHttpClient来获取内部资源。 在大多数情况下,我希望它使用其缓存,这似乎运行良好。 但是,定期使用客户端检查对特殊远程文件的更新(基本上它具有配置数据)。 在那种情况下,我希望能够告诉客户端通过HTTP来获取资源,即使缓存中包含该资源并且该资源尚未标记为过期。

当我在JavaScript中遇到这种情况时,通常会在其中附加带有时间戳的虚假查询字符串参数,以使URL与缓存的条目不匹配。 但是,我认为在这种情况下会有更好的解决方案,因为我们可以直接以编程方式访问HTTP客户端。

以免有人建议仅更改远程服务器,以便它设置Cache-Control: no-cache标头来防止这种情况,请理解,这不在我的控制范围之内。 目标是在这种情况下绕过缓存,而不管远程服务器是否说可以/应该缓存。

有人可能还会建议在这种情况下不要使用缓存HttpClient ,但这对我来说并不理想,因为那样的话,我就需要再创建一个HttpClient (此应用程序的其他部分需要对这些HTTP资源进行缓存才能表现良好)。

编辑 :user3360944建议使用HttpCacheInvalidator ,这可能是正确的解决方案,但是我不确定如何做到这一点。 有人可以举一个例子,说明将什么放入flushInvalidatedCacheEntries方法中,以删除给定URL的缓存条目吗? (我有一些我不想缓存的特定URL)

new HttpCacheInvalidator() {
    @Override
    public void flushInvalidatedCacheEntries(HttpHost host, HttpRequest req) {
        // What do I need to do here to invalidate a cached entry for
        // say, http://www.example.com/path/file.txt?
    }

    @Override
    public void flushInvalidatedCacheEntries(HttpHost host, HttpRequest request, HttpResponse response) {        
        // Do nothing here since I don't need to invalidate anything
        // based on the response received
    }
}

由于您具有CachingHttpClientBuilder,因此可以通过此方法将其配置为使用特定的HttpCacheInvalidator。

setHttpCacheInvalidator(HttpCacheInvalidator cacheInvalidator) 

如果需要响应的未缓存版本,则可以在发出请求之前使用HttpCachedInvalidator使请求无效。

它将涉及一些自定义代码,但是可以通过稍微调整HttpClient的执行管道来完全绕过缓存层。

class ConditionalCachingExec implements ClientExecChain {

    private final ClientExecChain mainExec;
    private final ClientExecChain cachingExec;

    public ConditionalCachingExec(final ClientExecChain mainExec, final ClientExecChain cachingExec) {
        this.mainExec = mainExec;
        this.cachingExec = cachingExec;
    }

    @Override
    public CloseableHttpResponse execute(
            final HttpRoute route,
            final HttpRequestWrapper request,
            final HttpClientContext clientContext,
            final HttpExecutionAware execAware) throws IOException, HttpException {
        URI uri = request.getURI();
        if ("/stuff".equals(uri.getPath())) {
            return mainExec.execute(route, request, clientContext, execAware);
        } else {
            return cachingExec.execute(route, request, clientContext, execAware);
        }
    }

};

class MyCachingHttpClientBuilder extends CachingHttpClientBuilder {

    @Override
    protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) {
        ClientExecChain cachingExec = super.decorateMainExec(mainExec);
        return new ConditionalCachingExec(mainExec, cachingExec);
    }

};


CloseableHttpClient httpClient = new MyCachingHttpClientBuilder().build();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM