静态资源缓存
采用Spring Boot开发Web项目时,静态文件(css、js)每次都会从服务器加载。Spring boot可设置静态文件缓存,设置方式可通过配置文件或者配置类实现。
参考
https://docs.spring.io/spring-boot/docs/2.0.0.M2/reference/htmlsingle/ SPRING RESOURCES HANDLING
https://docs.spring.io/spring-boot/docs/2.0.0.M2/reference/htmlsingle/#boot-features-spring-mvc-static-content
通过配置文件配置
#配置静态资源映射
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static
# 资源缓存时间,单位秒,30天
spring.resources.cache-period=2592000
# 开启gzip压缩
spring.resources.chain.gzipped=true
# 启用缓存
spring.resources.chain.cache=true
# Enable the Spring Resource Handling chain. Disabled by default
spring.resources.chain.enabled=true
# 开启版本控制策略,默认为false
spring.resources.chain.strategy.content.enabled=true
# 指定要应用的版本的路径,多个以逗号分隔,默认为:[/**]
spring.resources.chain.strategy.content.paths=/**
# 设定Session的追踪模式(cookie, url, ssl)
server.session.tracking-modes=cookie
通过配置类配置
@Configuration
//@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
<span class="hljs-meta">@Autowired</span>
<span class="hljs-keyword">private</span> StringHashCacheData stringCacheService;
<span class="hljs-comment">/**
* 配置静态资源
* 此处可使用 properties 文件配置
* <span class="hljs-doctag">@param</span> registry
*/</span>
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addResourceHandlers</span><span class="hljs-params">(ResourceHandlerRegistry registry)</span> </span>{
VersionResourceResolver versionResourceResolver = <span class="hljs-keyword">new</span> VersionResourceResolver()
.addVersionStrategy(<span class="hljs-keyword">new</span> ContentVersionStrategy(), <span class="hljs-string">"/**"</span>);
registry.addResourceHandler(<span class="hljs-string">"static/**"</span>)
.addResourceLocations(<span class="hljs-string">"classpath:/static/"</span>)
.setCachePeriod(<span class="hljs-number">2592000</span>).resourceChain(<span class="hljs-keyword">true</span>)
.addResolver(versionResourceResolver);
}