gpt4 book ai didi

java - 如何使用 littleproxy/netty 缓存流量?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:46 25 4
gpt4 key购买 nike

我想用littleproxy缓存静态文件。所以我用 uri 的键和响应主体的值创建了 HashMap。这是 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 中的响应有问题。当浏览器首先访问静态文件时,控制台中会出现一条调试消息:已添加到缓存中。当浏览器第二次访问静态文件时,会出现一条消息:“GOT FROM CACHE”,但浏览器会一直旋转以等待响应。

保存和存储来自服务器的响应并在需要时将其返回给客户端的正确方法是什么?

最佳答案

我认为您还需要复制 FullHttpResponse 以确保您拥有正确的作者/读者索引。

cache.put(requestUri, response.duplicate().retain());

和:

返回 cache.get(requestUri).duplicate();

还要确保在从缓存中删除内容后调用 release()

关于java - 如何使用 littleproxy/netty 缓存流量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44985182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com