java Spring Boot 响应压缩不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38434834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring boot response compression not working
提问by Quan Ding
I have some javascript bundled file that is pretty big, ~1MB. I'm trying to turn on response compression with the following application properties in my yml file:
我有一些相当大的 javascript 捆绑文件,大约 1MB。我正在尝试在我的 yml 文件中使用以下应用程序属性打开响应压缩:
server.compression.enabled: true
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css
But it doesn't work. No compression is happening.
但它不起作用。没有发生压缩。
Request headers:
请求头:
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Response headers
响应头
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Connection:keep-alive
Content-Length:842821
Content-Type:application/javascript;charset=UTF-8
There's no content encoding header in the response.
响应中没有内容编码标头。
I'm using spring boot version 1.3.5.RELEASE
我正在使用 Spring Boot 版本 1.3.5.RELEASE
What am I missing?
我错过了什么?
=== EDIT 4 === I was planning to create a stand alone app to investigate further why content compression properties weren't working. But all of sudden it started working and I haven't changed any thing configuration-wise, not POM file change, not application.yml file change. So I don't know what has changed that made it working...
=== EDIT 4 === 我计划创建一个独立的应用程序来进一步调查为什么内容压缩属性不起作用。但突然间它开始工作了,我没有更改任何配置,不是 POM 文件更改,不是 application.yml 文件更改。所以我不知道是什么改变了它的工作......
===EDIT 3===follow @chimmi's suggestions further. I've put break points in the suggested places. It looks like requests to static resources (js files) never stopped at those break points. Only rest API requests do. And for those request, the content-length was zero for some reason which causes the content compression to be skipped.
===编辑3===进一步遵循@chimmi 的建议。我在建议的地方放置了断点。看起来对静态资源(js 文件)的请求从未在这些断点处停止过。只有其余 API 请求可以。对于那些请求,由于某种原因导致内容压缩被跳过,内容长度为零。
===EDIT 2===I've put a break point at line 180 of o.s.b.a.w.ServerProperties thanks to @chimmi's suggestion and it shows that all the properties are set but somehow the server doesn't honor the setting... :(
===EDIT 2===由于@chimmi 的建议,我在 osbawServerProperties 的第 180 行设置了一个断点,它显示所有属性都已设置,但不知何故服务器不遵守该设置... :(
===EDIT 1===
===编辑1===
not sure if it matters, but I'm pasting my application main and configuration code here:
不确定它是否重要,但我在此处粘贴我的应用程序主代码和配置代码:
Application.java:
应用程序.java:
@SpringBootApplication
public class TuangouApplication extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(TuangouApplication.class, args);
}
// this is for WAR file deployment
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(TuangouApplication.class);
}
@Bean
public javax.validation.Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
}
Configuration:
配置:
@Configuration
public class TuangouConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**").permitAll()
.and().antMatcher("/**").authorizeRequests().antMatchers("/api/**").permitAll()
.and().exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
.and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
.and().logout().logoutSuccessUrl("/").permitAll()
.and().csrf().csrfTokenRepository(csrfTokenRepository())
.and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class)
.headers().defaultsDisabled().cacheControl();
// @formatter:on
}
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public UserDetailsService userDetailsService() {
return new DatabaseUserServiceDetails();
}
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request
.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null
|| token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
Resource server config:
资源服务器配置:
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter{
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources)
throws Exception {
resources.tokenStore(tokenStore);
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/api/**").permitAll();
// @formatter:on
}
}
回答by Patryk Dobrzyński
Maybe the problem is with YAML configuration.
If you use ‘Starters' SnakeYAML will be automatically provided via spring-boot-starter
. If you don't - you must use properties convention in application.properties.
Using YAML instead of Properties
也许问题出在 YAML 配置上。如果您使用“Starters”,SnakeYAML 将通过spring-boot-starter
. 如果不这样做 - 您必须在 application.properties 中使用属性约定。
使用 YAML 而不是属性
EDIT:Try with this in your yml file:
编辑:在你的 yml 文件中试试这个:
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css,application/javascript,application/json
min-response-size: 1024
回答by Patryk Dobrzyński
If you use non-embedded Tomcat you should add this to your server.xml:
如果您使用非嵌入式 Tomcat,您应该将其添加到您的 server.xml 中:
compression="on"
compressionMinSize="2048"
compressableMimeType="text/html,text/xml,application/javascript"
回答by Gandalf
Never had much luck with the Spring Boot compression. A simple solution could be to use a third party library like ziplet.
Spring Boot 压缩从来没有好运。一个简单的解决方案可能是使用第三方库,如 ziplet。
Add to pom.xml
添加到 pom.xml
<dependency>
<groupId>com.github.ziplet</groupId>
<artifactId>ziplet</artifactId>
<version>2.0.0</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
Add to your @Config class :
添加到您的 @Config 类:
@Bean
public Filter compressingFilter() {
return new CompressingFilter();
}
回答by s.a.hosseini
you have to enable ssl
like http2 mode, response compression (Content-Encoding) can work, when ssl mode is configured.
您必须像 http2 模式一样启用 ssl,当配置了 ssl 模式时,响应压缩(内容编码)才能工作。
response compression
响应压缩
application.yml
应用程序.yml
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css, application/javascript, application/json
min-response-size: 1024
ssl:
enabled: true
key-store: keystore.p12
key-store-password: pass
keyStoreType: PKCS12
keyAlias: name
spring:
resources:
chain:
gzipped: true
回答by abaghel
Did you try with different browsers? That could be because of antivirus which is unzipping the file as mentioned in the SO post Spring boot http response compression doesn't work for some User-Agents
您是否尝试过使用不同的浏览器?这可能是因为防病毒软件正在解压缩文件,如 SO post Spring Boot http 响应压缩对某些用户代理不起作用