Skip to content

Commit

Permalink
Merge pull request #65 from jamebal/share
Browse files Browse the repository at this point in the history
perf: 优化"Cache-Control", 文本文件不缓存, 其他文件缓存30天
  • Loading branch information
jamebal authored May 27, 2024
2 parents 606b869 + 3028b8e commit 7e7526a
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 22 deletions.
13 changes: 5 additions & 8 deletions src/main/java/com/jmal/clouddisk/config/WebConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.http.CacheControl;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
* WebConfig
Expand Down Expand Up @@ -44,12 +45,8 @@ public void addInterceptors(InterceptorRegistry registry) {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/*/Image/**")
.addResourceLocations("file:" + fileProperties.getRootDir() + File.separator)
.setCacheControl(CacheControl.maxAge(7, TimeUnit.DAYS));
registry.addResourceHandler("/file/**")
.addResourceLocations("file:" + fileProperties.getRootDir() + File.separator)
.setCacheControl(CacheControl.noCache());
.addResourceLocations("file:" + fileProperties.getRootDir() + File.separator);
log.info("静态资源目录:{}", fileProperties.getRootDir() + File.separator);
}

Expand Down
21 changes: 8 additions & 13 deletions src/main/java/com/jmal/clouddisk/interceptor/FileInterceptor.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.jmal.clouddisk.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.text.CharSequenceUtil;
Expand All @@ -15,6 +14,7 @@
import com.jmal.clouddisk.service.IShareService;
import com.jmal.clouddisk.util.CaffeineUtil;
import com.jmal.clouddisk.util.FileContentTypeUtils;
import com.jmal.clouddisk.util.MyFileUtils;
import com.luciad.imageio.webp.WebPWriteParam;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -106,6 +106,7 @@ public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServl
Path path = Paths.get(request.getRequestURI());
String encodedFilename = URLEncoder.encode(String.valueOf(path.getFileName()), StandardCharsets.UTF_8);
String operation = request.getParameter(OPERATION);
setCacheControl(request, response);
if (!CharSequenceUtil.isBlank(operation)) {
switch (operation) {
case DOWNLOAD -> {
Expand All @@ -124,30 +125,24 @@ public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServl
case THUMBNAIL -> thumbnail(request, response);
case WEBP -> webp(request, response);
default -> {
setImageCacheControl(request, response);
return true;
}
}
} else {
setImageCacheControl(request, response);
return !previewOssFile(request, response, path, encodedFilename);
}
setImageCacheControl(request, response);
return true;
}

private void setImageCacheControl(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) {
private void setCacheControl(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) {
File file = getFileByRequest(request);
String contentType = FileContentTypeUtils.getContentType(FileTypeUtil.getType(file));
if (contentType.contains("image")) {
setCacheControl(response);
if (MyFileUtils.checkNoCacheFile(file)) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache");
} else {
response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=2592000");
}
}

private static void setCacheControl(@NotNull HttpServletResponse response) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=2592000");
}

/**
* 预览oss文件
*/
Expand Down Expand Up @@ -346,7 +341,7 @@ private void responseHeader(HttpServletResponse response, String fileName, byte[
}
response.setHeader(HttpHeaders.CONNECTION, "close");
response.setHeader(HttpHeaders.CONTENT_ENCODING, "utf-8");
setCacheControl(response);
response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=2592000");
}

/**
Expand Down
32 changes: 32 additions & 0 deletions src/main/java/com/jmal/clouddisk/util/MyFileUtils.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.jmal.clouddisk.util;

import cn.hutool.core.io.CharsetDetector;
import cn.hutool.core.io.FileTypeUtil;

import java.io.File;
import java.nio.charset.Charset;
Expand All @@ -26,6 +27,37 @@ public static Charset getFileCharset(File file) {
Charset charset = CharsetDetector.detect(file, StandardCharsets.UTF_8);
return charset == null ? StandardCharsets.UTF_8 : charset;
}

public static boolean checkNoCacheFile(File file) {
try {
if (file == null) {
return false;
}
if (!file.isFile() || file.length() < 1) {
return false;
}
String type = FileTypeUtil.getType(file);
if ("pdf".equals(type)) {
return true;
}
if ("ppt".equals(type) || "pptx".equals(type)) {
return true;
}
if ("doc".equals(type) || "docx".equals(type)) {
return true;
}
Charset charset = CharsetDetector.detect(file);
if (charset == null) {
return false;
}
if ("UTF-8".equals(charset.toString())) {
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
}


2 changes: 1 addition & 1 deletion src/main/resources/file.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ file:
# FTP server 端口号
ftpServerPort: 8089
# 文本类型
simText: [ txt, html, htm, xhtml, css, less, sass, scss, js, ts, jsx, tsx, json, xml, csv, tsv, md, markdown, rst, yaml, yml, ini, toml, cfg, conf, log, bat, cmd, sh, bash, zsh, ps1, py, pyw, pyc, pyo, pyd, rb, erb, pl, pm, t, php, phtml, phps, java, jsp, jspx, jsf, jws, jsp, jtpl, scala, kt, kts, groovy, gvy, gy, gsh, swift, c, cc, cpp, cxx, h, hh, hpp, hxx, cs, csx, vb, fs, fsx, fsi, ml, mli, go, rs, rlib, d, asm, s, sql, pgsql, psql, plpgsql, pls, plb, plsql, sqlite, db, dbf, mdb, accdb, cbl, cob, cpy, tcl, tk, lua, hs, erl, hrl, ex, exs, clj, cljs, edn, lisp, lsp, scm, rkt, ss, sml, v, sv, svh, vhd, vhdl, ino, pde, bsv, f, f90, f95, f03, f08, for, f77, f18, vba, vb, bas, cls, frm, frx, tex, latex, ltx, bib, bbl, sty, cls, dtx, ins, rst, rest, org, asciidoc, adoc, asc, pod, pov, mmd, mn, muse, creole, wiki, dokuwiki, vimwiki, haddock, jsdoc, pydoc, rdoc, yard, doxygen, roxygen2, javadoc, xmldoc, html, xhtml, htm, shtm, shtml, mht, mhtml, hdml, tpl, tmpl, vue, ejs, hbs, haml, pug, jade, slim, mustache, handlebars, nunjucks, liquid, jinja2, jinja, jnj, j2, njk, twig, swig, poi, t4, tt, tt2, tpl, eta, ect, coffee, litcoffee, dart, diff, patch, hs, x, xi, xmi, xaml, kml, wsdl, plist, nfo, srt, sub, sbv, vtt, bml, mrl, irl, log, changelog, CHANGELOG, license, LICENCE, LICENSE, copying, COPYING, readme, README, todo, TODO, contributing, CONTRIBUTING, authors, AUTHORS, dockerfile, Dockerfile, code-workspace, jsconfig, tsconfig, jshintrc, jscsrc, eslintrc, eslintignore, babelrc, browserconfig, webmanifest, htaccess, gitlab-ci, travis, circleci, jenkinsfile, prettierrc, stylelintrc, lintstagedrc, commitlintrc ]
simText: [ drawio, mind, txt, html, htm, xhtml, css, less, sass, scss, js, ts, jsx, tsx, json, xml, csv, tsv, md, markdown, rst, yaml, yml, ini, toml, cfg, conf, log, bat, cmd, sh, bash, zsh, ps1, py, pyw, pyc, pyo, pyd, rb, erb, pl, pm, t, php, phtml, phps, java, jsp, jspx, jsf, jws, jsp, jtpl, scala, kt, kts, groovy, gvy, gy, gsh, swift, c, cc, cpp, cxx, h, hh, hpp, hxx, cs, csx, vb, fs, fsx, fsi, ml, mli, go, rs, rlib, d, asm, s, sql, pgsql, psql, plpgsql, pls, plb, plsql, sqlite, db, dbf, mdb, accdb, cbl, cob, cpy, tcl, tk, lua, hs, erl, hrl, ex, exs, clj, cljs, edn, lisp, lsp, scm, rkt, ss, sml, v, sv, svh, vhd, vhdl, ino, pde, bsv, f, f90, f95, f03, f08, for, f77, f18, vba, vb, bas, cls, frm, frx, tex, latex, ltx, bib, bbl, sty, cls, dtx, ins, rst, rest, org, asciidoc, adoc, asc, pod, pov, mmd, mn, muse, creole, wiki, dokuwiki, vimwiki, haddock, jsdoc, pydoc, rdoc, yard, doxygen, roxygen2, javadoc, xmldoc, html, xhtml, htm, shtm, shtml, mht, mhtml, hdml, tpl, tmpl, vue, ejs, hbs, haml, pug, jade, slim, mustache, handlebars, nunjucks, liquid, jinja2, jinja, jnj, j2, njk, twig, swig, poi, t4, tt, tt2, tpl, eta, ect, coffee, litcoffee, dart, diff, patch, hs, x, xi, xmi, xaml, kml, wsdl, plist, list, nfo, srt, sub, sbv, vtt, bml, mrl, irl, log, changelog, CHANGELOG, license, LICENCE, LICENSE, copying, COPYING, readme, README, todo, TODO, contributing, CONTRIBUTING, authors, AUTHORS, dockerfile, Dockerfile, code-workspace, jsconfig, tsconfig, jshintrc, jscsrc, eslintrc, eslintignore, babelrc, browserconfig, webmanifest, htaccess, gitlab-ci, travis, circleci, jenkinsfile, prettierrc, stylelintrc, lintstagedrc, commitlintrc ]
# 文档类型
document: [ "pdf", "doc", "docx", "xlsx", "xls", "xl", "md", "ppt", "pptx" ]
# webDAV协议前缀
Expand Down

0 comments on commit 7e7526a

Please sign in to comment.