Cache and zip static resources with Spring Boot 2

核能气质少年 提交于 2020-01-16 04:45:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!