[英]Cache static files by content type in Spring Boot
我正在嘗試在 Spring Boot 中針對特定的 static 文件類型設置緩存標頭。 在目錄 src/main/resources/static 中有幾個不同文件類型的子目錄:
src/main/resources/static/font --> *.otf
src/main/resources/static/lib --> *.js
src/main/resources/static/images --> *.png, *.jpg
有沒有辦法在 Spring 配置中按文件類型放置緩存標頭?
*.otf 365 days
*.png 30 days
*.jpg 7 days
Spring 版本是 5.2.3 和 Spring Boot 2.2.4 - Spring Boot 是否有機會處理它並使其無法工作?
試過
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
final CacheControl oneYearPublic =
CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic();
// it does not "work" with "/static/fonts/"
registry
.addResourceHandler("/fonts/{filename:\\w+\\.otf}")
.setCacheControl(oneYearPublic);
}
但我得到奇怪的結果。 使用 DevTools 的網絡選項卡檢查時,我得到了這些標題:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
但是當我 go 直接到 URL 時,我得到 404
http://localhost/fonts/1952RHEINMETALL.otf
沒有任何配置我得到“no-store”Cache-Control header。
我已經設法為這個問題找到了一個可行的解決方案。 檢查 GitHub 回購https://github.com/alexsomai/cache-static-assets 。
這是應該工作的配置示例:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
Objects.requireNonNull(registry);
// could use either '/**/images/{filename:\w+\.png}' or '/**/images/*.png'
registry.addResourceHandler("/**/images/{filename:\\w+\\.png}")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.DAYS));
registry.addResourceHandler("/**/images/*.jpg")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(2, TimeUnit.DAYS));
registry.addResourceHandler("/**/lib/*.js")
.addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(3, TimeUnit.DAYS));
}
}
您可以根據文件類型和緩存持續時間輕松地根據需要調整它。
作為關鍵要點,確保添加addResourceLocations
function(沒有這個,你會得到 404)。 另外,如果您使用的是 Spring Boot,則不需要@EnableWebMvc
,因為它最初發布在此示例https://stackoverflow.com/a/33216168/6908551中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.