java – Jersey中的Cache方法逻辑
发布时间:2020-12-15 02:16:00 所属栏目:Java 来源:网络整理
导读:我在各种类中都有几种GET方法.计划为所有这些引入缓存. 逻辑就是这样的. @GET@Path("/route1") { String cacheKey = routePathWithParams; if (cache.get(cacheKey) != null) { return cache.get(cacheKey); } else { // call servcie and get response cach
我在各种类中都有几种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); } } } 但无论如何都会采取行动 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |