SpringBoot实现缓存静态资源。
主要是使用tomcat的ExpiresFilter来实现,我们初始化ExpiresFilter过滤器即可
@Bean public FilterRegistrationBean basicFilterRegistrationBean() { FilterRegistrationBean registrationBean = new FilterRegistrationBean(); ExpiresFilter expiresFilter = new ExpiresFilter(); registrationBean.setFilter(expiresFilter); registrationBean.addInitParameter("ExpiresByType image", "access plus 30 minutes"); registrationBean.addInitParameter("ExpiresByType text/css", "access plus 30 minutes"); registrationBean.addInitParameter("ExpiresByType text/javascript", "access plus 30 minutes"); registrationBean.addInitParameter("ExpiresByType application/javascript", "access plus 30 minutes"); List<String> urlPatterns = new ArrayList<String>(); urlPatterns.add("/*"); registrationBean.setOrder(0); registrationBean.setUrlPatterns(urlPatterns); registrationBean.setDispatcherTypes(DispatcherType.REQUEST); return registrationBean; }
这里设置的是缓存30分钟,主要缓存文件有image、css、javascript的信息
注意:
如果静态资源目录不是默认的resources等目录,需要指定下目录
@Bean public WebMvcConfigurerAdapter webMvcConfigurerAdapter() { WebMvcConfigurerAdapter wmca = new WebMvcConfigurerAdapter() { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); super.addResourceHandlers(registry); } }; return wmca; }
上面的static为静态资源所在的目录