2016-07-18 63 views
18

我有一些相當大的JavaScript捆綁文件,〜1MB。 我想在我的陽明文件中的以下應用程序屬性開啓響應壓縮:春季開機響應壓縮不起作用

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 

有一個在響應中沒有內容編碼報頭。

我使用的彈簧引導版本1.3.5.RELEASE

我缺少什麼?

===編輯4 === 我打算創建一個獨立的應用程序來進一步調查爲什麼內容壓縮屬性不起作用。 但突然它開始工作,我沒有改變任何配置明智的東西,不POM文件的變化,而不是application.yml文件的變化。所以,我不知道發生了什麼變化,使得它的工作...

===編輯=== 3 後續@ chimmi的建議進一步。我在建議的地方放置了斷點。它看起來像對靜態資源(js文件)的請求從未停止在這些中斷點。只有其他API請求才能做到。對於這些請求,由於某些原因導致內容壓縮被跳過,內容長度爲零。

enter image description here

=== EDIT 2 === 我把一個破發點,在感謝osbawServerProperties 180線@ chimmi的建議,並表示所有的屬性設置,但不知該服務器不兌現設置... :(

Printing the Compression object at o.s.b.a.w.ServerProperties line 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

你檢查這SO -http://stackoverflow.com/questions/21410317/using-gzip -compression-with-spring-boot-mvc-javaconfig -with-restful – aksappy

+0

@aksappy是的,我做到了。我根據該鏈接的答案#2解決了我的解決方案。 –

+0

您的請求標頭有'keep-alive',表示HTTP 1.0,但引用的解決方案使用'AbstractHttp11Protocol'。也許你需要發送HTTP 1.1請求? – heenenee

回答

2

如果您使用非嵌入式Tomcat,應該將其添加到您的服務器。XML:

compression="on" 
compressionMinSize="2048" 
compressableMimeType="text/html,text/xml,application/javascript" 

More tomcat 8 config variables

+0

我猜他沒有server.xml,因爲他使用彈簧啓動 –

+0

@ benjamin.d正確。我沒有server.xml。 –

+0

我遇到同樣的問題...我將Spring Boot REST應用程序部署到AWS Elastic Beanstalk(Tomcat實例),因此沒有server.xml。即使我指定'Accept-Encoding:gzip,deflate',我在響應中看不到'Content-Encoding'。我如何解決這個問題? –

2

也許問題是與YAML配置。 如果您使用'Starters'SnakeYAML將通過spring-boot-starter自動提供。如果您不這樣做 - 您必須在application.properties中使用屬性約定。 Using YAML instead of Properties

編輯: 這種嘗試在陽明文件:

server: 
     compression: 
     enabled: true 
     mime-types: text/html,text/xml,text/plain,text/css,application/javascript,application/json 
     min-response-size: 1024 
+0

我嘗試了@chimmi建議的斷點方法,它顯示所有屬性都是由彈簧引導容器讀取的(我已經用屏幕截圖更新了我的原始文章),但它們被忽略了...... –

1

從來沒有很多運氣與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(); 
}