我在各种类中都有几种GET方法.计划为所有这些引入缓存.
逻辑就是这样的.
@GET
@Path("/route1") {
String cacheKey = routePathWithParams;
if (cache.get(cacheKey) != null) {
return cache.get(cacheKey);
} else {
// call servcie and get response
cache.put(cacheKey, response)
return response;
}
}
我不想把这个逻辑放在所有的GET方法中.哪个是最好的地方.
我可以使用过滤器吗?
public class CacheFilter implements ContainerRequestFilter, ContainerResponseFilter {
public void filter(ContainerRequestContext req) throws IOException {
// frame cacheKey from url and params
if (cache.get(cacheKey) != null) {
// return response from here. How to do it ???
} else {
//forward the request How to do it ???
}
}
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
// frame cachekey and put response
cache.put(cacheKey, response)
}
}
或者有更好的方法来做到这一点.
基本上这个问题不是关于客户端缓存或向用户发送缓存头.
基本上我试图在路由方法中缓存内部服务调用.
解决方法:
我正在尝试这样的事情
public class CachedInterceptor implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
OutputStream outputStream = context.getOutputStream();
String key = "key";
try {
byte[] entity = cache.get(key);
if (entity == null) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
context.setOutputStream(buffer);
context.proceed();
entity = buffer.toByteArray();
cache.put(key, entity);
}
outputStream.write(entity);
} finally {
context.setOutputStream(outputStream);
}
}
}
但无论如何都会采取行动