Java – cache method logic in Jersey
•
Java
I have several get methods in various classes Plan to introduce caching for all of these
Logic is like this
@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; } }
I don't want to put this logic in all get methods Which is the best place
Can I use the filter?
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) } }
Or there are better ways to do this Basically, this problem is not about client caching or sending cache headers to users
Basically, I try to cache internal service calls in routing methods
Solution
I'm trying something like this
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); } } }
But action will be taken anyway
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码