泽西岛的缓存方法逻辑

问题描述:

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

    } 
} 

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

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

+0

你怎么打算缓存失效? –

+0

@CássioMazzochiMolin将在密钥上设置缓存过期时间。所以一旦密钥过期,我会再次调用内部服务并将其缓存为固定的时间间隔。 – sanjeev

我想这样的事情

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

但行动反正叫