1.1后端压缩
@GetMapping(value = "/data", produces = "application/json")
public void getData(HttpServletResponse response) throws IOException {
String data = "your large data here"; // Replace with actual large data
response.setHeader("Content-Encoding", "gzip");
response.setContentType("application/json");
try (OutputStream os = response.getOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(os)) {
gzipOutputStream.write(data.getBytes());
}
}
1.2前端解压
fetch('/api/data', {
headers: {
'Accept-Encoding': 'gzip'
}
})
.then(response => {
if (response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
})
.then(blob => {
const reader = new FileReader();
reader.onload = () => {
const decompressedData = pako.inflate(reader.result, { to: 'string' });
console.log(JSON.parse(decompressedData));
};
reader.readAsArrayBuffer(blob);
})
.catch(error => {
console.error('There was a problem with your fetch operation:', error);
});
1.3 满足最小响应大小(2KB)和指定MIME类型的响应进行GZIP压缩
将为JSON、XML、文本和JavaScript以及CSS等类型的响应启用GZIP压缩,并且响应大小至少需要2KB才会被压缩
yml配置
# application.yml
server:
compression:
enabled: true
mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
min-response-size: 2048
自定义配置或者使用Java配置
创建了一个ShallowEtagHeaderFilter bean和一个GzipCompressingFilter bean,后者会对满足最小响应大小(2KB)和指定MIME类型的响应进行GZIP压缩
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import java.util.Arrays;
import java.util.List;
@Configuration
public class GzipConfig {
@Bean
public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
return new ShallowEtagHeaderFilter();
}
@Bean
public GzipCompressingFilter gzipCompressingFilter() {
GzipCompressingFilter filter = new GzipCompressingFilter();
filter.setMinGzipSize(2048);
List<String> mimeTypes = Arrays.asList("text/html", "text/xml", "text/plain", "text/css", "application/javascript", "application/json", "application/xml");
filter.setMimeTypes(mimeTypes);
return filter;
}
}