我想用littleproxy缓存静态文件。所以我创建了HashMap,其中包含uri的键和响应体的值。这里是java代码:
private static Map<String, FullHttpResponse> cache = new HashMap<>();
private static HttpFiltersSource getHttpFiltersSource() {
return new HttpFiltersSourceAdapter() {
@Override
public int getMaximumResponseBufferSizeInBytes() {
return 10 * 1024 * 1024;
}
public HttpFilters filterRequest(HttpRequest originalRequest, ChannelHandlerContext ctx) {
return new HttpFiltersAdapter(originalRequest) {
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
if (httpObject instanceof HttpRequest) {
HttpRequest request = (HttpRequest) httpObject;
String requestUri = request.getUri();
if(requestUri.matches(".*[./]png.*$") ||
requestUri.matches(".*[./]jpg.*$") ||
requestUri.matches(".*[./]jpeg.*$") ||
requestUri.matches(".*[./]woff2.*$") ||
requestUri.matches(".*[./]js.*$") ) {
if (cache.containsKey(requestUri)) {
System.out.println("GOT FROM CACHE " + requestUri);
return cache.get(requestUri);
}
}
}
return null;
}
@Override
public HttpObject serverToProxyResponse(HttpObject httpObject) {
if (httpObject instanceof FullHttpResponse) {
FullHttpResponse response = (FullHttpResponse) httpObject;
String requestUri = originalRequest.getUri();
if(requestUri.matches(".*[./]png.*$") ||
requestUri.matches(".*[./]jpg.*$") ||
requestUri.matches(".*[./]jpeg.*$") ||
requestUri.matches(".*[./]woff2.*$") ||
requestUri.matches(".*[./]js.*$") ) {
cache.put(requestUri, response.retain());
System.out.println("ADDED TO CACHE " + requestUri);
}
}
return httpObject;
}
};
}
};
}
但是Map中的响应有问题。当浏览器首先到达静态文件时,控制台中会出现一条调试消息:ADDED TO CACHE。当浏览器第二次到达静态文件时,会显示一条消息:&#34; GOT FROM CACHE&#34;,但浏览器会永远等待响应。
什么是从服务器保存和存储响应的正确方法,并在时间到来时将其返回给客户端?
答案 0 :(得分:0)
我认为你还需要复制FullHttpResponse
以确保你有正确的作者/读者索引。
cache.put(requestUri, response.duplicate().retain());
和
return cache.get(requestUri).duplicate();
还要确保在从缓存中删除内容后调用release()
。