我有一些相当大的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
但它不起作用。没有压缩发生。
请求标题:
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
回复标题
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Connection:keep-alive
Content-Length:842821
Content-Type:application/javascript;charset=UTF-8
响应中没有内容编码标头。
我正在使用spring boot版本1.3.5.RELEASE
我错过了什么?
===编辑4 === 我打算创建一个独立的应用程序,以进一步调查内容压缩属性无法正常工作的原因。 但突然之间它开始工作了,我没有改变配置方面的任何事情,不是POM文件更改,而不是application.yml文件更改。所以我不知道是什么改变了它使它工作......
===编辑3 === 请进一步关注@ chimmi的建议。我在建议的地方放了断点。看起来对静态资源(js文件)的请求从未在这些断点处停止。只有休息API请求才能执行。对于那些请求,由于某种原因,内容长度为零,导致内容压缩被跳过。
===编辑2 === 由于@ chimmi的建议,我在o.s.b.a.w.ServerProperties的第180行设置了一个断点,它显示所有属性都已设置但不知何故服务器不遵守设置...... :(
===编辑1 ===
不确定是否重要,但我在这里粘贴我的应用程序主要和配置代码:
Application.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
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;
}
}
资源服务器配置:
@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
}
}
答案 0 :(得分:2)
如果您使用非嵌入式Tomcat,则应将其添加到server.xml:
compression="on"
compressionMinSize="2048"
compressableMimeType="text/html,text/xml,application/javascript"
答案 1 :(得分:2)
可能问题出在YAML配置上。
如果您使用'初学者',将通过spring-boot-starter
自动提供SnakeYAML。如果不这样做 - 您必须在application.properties中使用属性约定。
Using YAML instead of Properties
修改强> 在yml文件中尝试使用它:
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,text/css,application/javascript,application/json
min-response-size: 1024
答案 2 :(得分:2)
Spring Boot压缩从未如此幸运。一个简单的解决方案可能是使用第三方库,如ziplet。
添加到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>
添加到@Config类:
@Bean
public Filter compressingFilter() {
return new CompressingFilter();
}
答案 3 :(得分:1)
你尝试过不同的浏览器吗?这可能是因为反病毒文件解压缩了文件,如SO Spring boot http response compression doesn't work for some User-Agents
中提到的那样答案 4 :(得分:0)
您必须启用ssl
与http2模式一样,在配置了ssl模式后,响应压缩(Content-Encoding)可以工作。
application.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