Jersey中的缓存方法逻辑

时间:2016-08-05 12:58:07

标签: java jersey jersey-2.0

我在各种类中都有几种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)

    }
}

或者有更好的方法来做到这一点。 基本上这个问题不是关于客户端缓存或向用户发送缓存头。

基本上我正在尝试在路由方法中缓存内部服务调用。

1 个答案:

答案 0 :(得分:0)

我正在尝试这样的事情

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

但无论如何都要采取行动