Spring boot Web 实现静态资源缓存

第一种方法,手动配置版本号

首先定义一个ControllerConfig配置类将路径信息在启动的时候推到前端

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.resource.ResourceUrlProvider;

/**
 *  使用ResourceUrlProvider进行版本管理
 *  并避免在版本发生改变时,由于浏览器缓存而产生资源版本未改变的错误
 */
@ControllerAdvice
public class ControllerConfig {

    @Autowired
    private ResourceUrlProvider resourceUrlProvider;

    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }

}

Springboot在静态文件的默认处理已经指定了classpath:/resources/static

在application.properties配置文件中加入以下配置

# 资源缓存时间,单位秒
spring.resources.cache-period=604800
# 开启gzip压缩
spring.resources.chain.gzipped=true
# 启用缓存
spring.resources.chain.cache=true

spring.resources.chain.strategy.fixed.enabled=true
# Springboot在静态资源的处理上已经默认做了处理,
# 直接指定/**表示该文件夹下的所有静态资源都做缓存处理
spring.resources.chain.strategy.fixed.paths=/**
# 指定版本号,每次打包更新的时候需要变更当前版本
spring.resources.chain.strategy.fixed.version=v1.0.0

前端页面上,这样引入js和css文件

<link rel="stylesheet" href="${urls.getForLookupPath('/bootstrap/css/bootstrap.min.css')}">
<script src="${urls.getForLookupPath('/jquery/jquery.js')}"></script>

这样你启动项目后页面上就实现了缓存
可以看到页面上引用的js文件路径变成了以下方式

http://192.16.0.98:8089/v1.0.0/layer/layer.js

加上缓存配置后我们访问页面后,被加载过的静态资源就会缓存起来,第二次访问时就不会再去重新请求下载了,通过抓包可以看出确实被缓存了。

如果你在本地调试代码时需要在浏览器上打开F12
在Network的Disable cache选项上打勾禁用缓存

这个方法有一个bug,就是你引入的js文件中引用了css,css中又引用了图片,那么该图片就会找不到报404错误

比如我引入了layer.js文件,而layer.css并没有使用版本管理的方法引入
css是在js代码中引入的,而图片又是在css中引入

<script src="${urls.getForLookupPath('/layer/layer.js')}"></script>

打开layer.js代码可以看到如下

从页面上可以看出图片的文件路径变为

http://10.16.0.98:8097/v1.0.0/layer/skin/default/v1.0.0/loading-2.gif

路径不正确所以loading-2.gif文件找不到,不推荐使用这个方法

第二种方法,使用MD5生成版本号进行管理

这个方法其实和第一种方法差不多的配置
只需要把application.properties配置信息修改一下,其它地方写法不变

spring.resources.chain.strategy.fixed.enabled=true

spring.resources.chain.strategy.fixed.paths=/**

spring.resources.chain.strategy.fixed.version=v1.0.0

把这三条配置删掉,换成MD5生成就可以了

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

可以看到引用图片正常

路径引用变成以下方式

http://192.16.0.98:8089/layer/skin/default/loading-2-50c5e3e79b276c92df6cc52caeb464f0.gif

项目不管是打包部署还是本地调试只要refresh的时候,就会产生一个新的MD5,这样客户端的资源路径就发生改变,回去服务器重新获取

猜你喜欢

转载自blog.csdn.net/m0_37845840/article/details/81382462