问题
I have a Spring Boot 2 application where static resources are:
src
|- main
|-resources
|-static
|-js/myjs.js
|-style
|-css/mycss.css
In my template file:
<link rel="stylesheet" type="text/css" href="/style/css/mycss.css">
<script src="/js/myjs.js"></script>
This is working fine.
However I want to enable browser cache and gzip transfer. To do this I have created the following WebConfig:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("/static/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new GzipResourceResolver())
.addResolver(new PathResourceResolver());
}
}
The app still works but no static content is cached nor gzipped:
Any idea what I'm doing wrong?
回答1:
server.compression.enabled=true
spring.resources.cache-period=3600
spring boot 2.0 change
spring.resources.cache-period=3600 to spring.resources.cache.period=3600
回答2:
With Spring Boot 2.0.0 I'm using following config:
server.compression.enabled=true
spring.resources.cache.cachecontrol.cache-public=true
spring.resources.cache.cachecontrol.no-cache=false
spring.resources.cache.cachecontrol.no-store=false
spring.resources.cache.cachecontrol.must-revalidate=false
spring.resources.cache.cachecontrol.max-age=31536000
回答3:
Finally I was able to solve it with simple application configuration:
server.compression.enabled=true
spring.resources.cache-period=3600
The WebConfig code was removed from the project.
Note: I have to note that Chrome still shows that content was not compressed but if I check the network traffic with Fiddler then it shows that all css and js files were compressed.
来源:https://stackoverflow.com/questions/47414098/cache-and-zip-static-resources-with-spring-boot-2