加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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);
        }
    }
}

但无论如何都会采取行动

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读