Jersey Cache Logic

I have several GET methods in different classes. Planning for caching implementations for all of these.

The logic will be something 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 do not want to put this logic in all GET methods. Which place is best suited.

Can I use filters?

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 is there a better way to do this. Basically this question is not about client-side caching or sending cache headers to the user.

I am mainly trying to cache internal service calls in route methods.

+4
source share
1 answer

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 the action is called anyway

0
source

Source: https://habr.com/ru/post/1650308/


All Articles