springboot 高效GZIP
时间: 2024-01-10 21:21:53 浏览: 184
SpringBoot静态资源处理共5页.pdf.zip
在Spring Boot中实现高效的GZIP压缩可以通过配置来实现。下面是一个示例:
1. 在`application.properties`或`application.yml`文件中添加以下配置:
```yaml
server.compression.enabled=true
server.compression.mime-types=application/json,application/xml,text/html,text/css,text/javascript,application/javascript
```
2. 在启动类中添加`@EnableCompression`注解:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.ShallowEtagHeaderFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.EnumSet;
@SpringBootApplication
@EnableWebMvc
public class BootDemoApplication implements WebMvcConfigurer, ServletContextInitializer {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
FilterRegistrationBean<CharacterEncodingFilter> characterEncodingFilter = new FilterRegistrationBean<>();
characterEncodingFilter.setFilter(new CharacterEncodingFilter());
characterEncodingFilter.addInitParameter("encoding", "UTF-8");
characterEncodingFilter.addInitParameter("forceEncoding", "true");
characterEncodingFilter.setDispatcherTypes(dispatcherTypes);
characterEncodingFilter.addUrlPatterns("/*");
FilterRegistrationBean<ShallowEtagHeaderFilter> shallowEtagHeaderFilter = new FilterRegistrationBean<>();
shallowEtagHeaderFilter.setFilter(new ShallowEtagHeaderFilter());
shallowEtagHeaderFilter.setDispatcherTypes(dispatcherTypes);
shallowEtagHeaderFilter.addUrlPatterns("/*");
servletContext.addFilter("characterEncodingFilter", characterEncodingFilter.getFilter()).addMappingForUrlPatterns(dispatcherTypes, true, "/*");
servletContext.addFilter("shallowEtagHeaderFilter", shallowEtagHeaderFilter.getFilter()).addMappingForUrlPatterns(dispatcherTypes, true, "/*");
}
@Bean
public FilterRegistrationBean<GzipFilter> gzipFilter() {
FilterRegistrationBean<GzipFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new GzipFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
```
请注意,上述示例中的`GzipFilter`是自定义的GZIP过滤器,你需要根据自己的需求实现该过滤器。
阅读全文