在Dropwizard中设置静态资产的缓存控制标头

时间:2013-11-18 16:20:05

标签: cache-control dropwizard

在Dropwizard服务中设置静态资产的缓存控制标头的最佳方法是什么?

一些谷歌搜索出现了一个AssetsBundle构造函数:

AssetsBundle(String resourcePath, com.google.common.cache.CacheBuilderSpec cacheBuilderSpec, String uriPath)

然而,经过进一步调查,看起来com.yammer.dropwizard.bundles软件包自版本5.1以来就不属于Dropwizard。

也许我错过了一些明显的东西,但有没有一种首选方法可以解决这个问题?

4 个答案:

答案 0 :(得分:9)

如果有人感兴趣(根据这个问题的观点数量判断,可能不是这样),这就是我解决这个问题的方法。

我在与Service类相同的包中创建了一个CacheControlFilter类:

public class CacheControlFilter implements Filter{

    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

        HttpServletResponse resp = (HttpServletResponse) response;

        // Add whatever headers you want here
        resp.setHeader("Cache-Control", "public, max-age=500000");
        resp.setHeader("Expires", new Date().getTime()+500000 + "");

        chain.doFilter(request, response);
    }

    public void destroy() {}

    public void init(FilterConfig arg0) throws ServletException {}
}

然后在服务类中,只需添加以下行:

env.addFilter(new CacheControlFilter(), "/*");

当然,您可以更精细地为图像文件和css文件添加不同的过滤器,但这会为所有请求添加标题。

来自评论:

for dropwizard 1.0.6。只需注册

env.servlets()
   .addFilter("MyFilter", new CacheControlFilter())
   .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*") 

答案 1 :(得分:2)

如果你只想清除每个请求的缓存,下面是我的解决方案,它使用DropWizard提供的CacheBustingFilter。

  1. 定义自定义配置,在我的例子中是WebConfiguration。在设置DropWizard应用程序时使用此配置。

    public class WebConfiguration extends Configuration {
    
    @JsonProperty
    private String enableCacheControl;
    
    public String getEnableCacheControl() {
        return enableCacheControl;
    }
    
    public void setEnableCacheControl(String enableCacheControl) {
        this.enableCacheControl = enableCacheControl;
    }
    

    }

  2. 获取您在#1中定义的配置,并根据其值注册CacheBustingFilter。

  3. 在运行方法中添加它 -

        // get the cache control settings from the YAML - configuration
        String enableCacheControl = configuration.getEnableCacheControl();
        boolean enableCacheBustingFilter = Boolean.parseBoolean(enableCacheControl);
    
        if(enableCacheBustingFilter){
            // caching was enabled in YAML - was set to true - enabling the cacheBustingFilter
            // this will ALWAYS return  "must-revalidate,no-cache,no-store" in the Cache-Control response header
            environment.servlets().addFilter("CacheBustingFilter", new CacheBustingFilter())
                .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
        }
    

答案 2 :(得分:1)

根据Tim Barclay的回答,我创建了一个过滤器,如果请求的资源是扩展名为js,css,png,jpg的文件,将在未来一年设置Cache-ControlExpires ,gif或svg。否则缓存被禁用。

希望它对某人有帮助!

protected void setCacheHeaders(Environment environment, String urlPattern, int seconds) {
    FilterRegistration.Dynamic filter = environment.servlets().addFilter(
            "cacheControlFilter",
            new Filter() {
                @Override
                public void init(FilterConfig filterConfig) throws ServletException {

                }

                @Override
                public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

                    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

                    String[] cacheFileTypes = {"js","css","png","jpg","gif","svg"};
                    String filetypeRequested = FilenameUtils.getExtension(httpServletRequest.getRequestURL().toString());

                    if (httpServletRequest.getMethod() == "GET" && seconds > 0 && Arrays.asList(cacheFileTypes).contains(filetypeRequested)) {
                        httpServletResponse.setHeader("Cache-Control", "public, max-age=" + seconds);
                        Calendar c = Calendar.getInstance();
                        c.setTime(new Date());
                        c.add(Calendar.SECOND, seconds);
                        SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz", Locale.US);
                        format.setTimeZone(TimeZone.getTimeZone("GMT"));
                        httpServletResponse.setHeader("Expires", format.format(c.getTime()));
                    } else {
                        httpServletResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                        httpServletResponse.setHeader("Expires", "0");
                        httpServletResponse.setHeader("Pragma", "no-cache");
                    }

                    filterChain.doFilter(servletRequest, servletResponse);

                }

                @Override
                public void destroy() {

                }
            }
    );
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, urlPattern);
}

PS:我无法获得接受答案的方法来设置Expires - 标头:

resp.setHeader("Expires", new Date().getTime()+500000 + "");

相比之下,我的表现非常臃肿,但它确实有效:

Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.SECOND, seconds);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
httpServletResponse.setHeader("Expires", format.format(c.getTime()));

答案 3 :(得分:0)

在新版本的Dropwizard @CacheControl注释中。

https://dropwizardio.readthedocs.io/en/v0.7.0/manual/core.html#caching