Jersey: Default Cache Control to no-cache

前端 未结 5 2294
孤独总比滥情好
孤独总比滥情好 2020-12-25 13:35

While writing a RESTful web service, I am encountering issues if I enable any sort of caching on my client (currently a .NET thick client). By default Jersey is not sending

5条回答
  •  误落风尘
    2020-12-25 14:01

    Based on the solution by @martin-matula I created two Cache annotations. One @NoCache for no caching at all and one @CacheMaxAge for specific caching. The CacheMaxAge takes two arguments so you don't have to calculate the seconds yourself:

    @GET
    @CacheMaxAge(time = 10, unit = TimeUnit.MINUTES)
    @Path("/awesome")
    public String returnSomethingAwesome() {
        ...
    }
    

    The ResourceFilter now has this create method that by default doesn't interfere (so other caching mechanisms keep working):

    @Override
    public List create(AbstractMethod am) {
        if (am.isAnnotationPresent(CacheMaxAge.class)) {
            CacheMaxAge maxAge = am.getAnnotation(CacheMaxAge.class);
            return newCacheFilter("max-age: " + maxAge.unit().toSeconds(maxAge.time()));
        } else if (am.isAnnotationPresent(NoCache.class)) {
            return newCacheFilter("no-cache");
        } else {
            return Collections.emptyList();
        }
    }
    
    private List newCacheFilter(String content) {
        return Collections
                . singletonList(new CacheResponseFilter(content));
    }
    

    You can see the full solution in my blogpost.

    Thanks for the solution Martin!

提交回复
热议问题