2016-07-18 4 views
18

저는 꽤 큰 자바 스크립트 번들 파일이 1MB 정도 있습니다.스프링 부트 응답 압축이 작동하지 않습니다.

server.compression.enabled: true 
server.compression.mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css 

을하지만 그것은 작동하지 않습니다 내 YML 파일에 다음 응용 프로그램 속성에 응답 압축을 설정하기 위해 노력하고있어. 압축이 일어나지 않습니다.

요청 헤더 :

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

을 사용하고

나는 무엇을 놓치고?

=== EDIT 4 === 콘텐츠 압축 속성이 작동하지 않는 이유를 조사하기 위해 독립 실행 형 응용 프로그램을 만들 계획이었습니다. 하지만 갑자기 작동하기 시작했는데 application -yml 파일 변경이 아니라 POM 파일 변경이 아니라 구성에 따라 변경되지 않았습니다. 그래서 나는 3 === 추종 @의 chimmi의 제안을 더

=== 수정 ... 작업을 만든 그 변경 사항을 알 수 없습니다. 제안 된 장소에 중단 점을 넣었습니다. 정적 리소스 (js 파일)에 대한 요청이 중단 점에서 중단되지 않은 것 같습니다. 나머지 API 요청 만 수행합니다. 그리고 이러한 요청에 대해 콘텐츠 길이가 0 인 이유로 콘텐츠 압축을 건너 뜁니다.

enter image description here

=== 편집 2 === 어떻게 든 내가 @ chimmi의 제안에 osbawServerProperties 덕분에 라인 (180)에 브레이크 포인트를 넣었습니다 그것은 모든 속성이 설정되어 있는지 표시하지만 서버는 EDIT 1 === ===

Printing the Compression object at o.s.b.a.w.ServerProperties line 180

:(... 설정을 존중하지 않는

,451,515,

확실하지가 중요한,하지만 난 여기에 내 응용 프로그램의 주요 및 구성 코드를 붙여 해요 경우 :

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 확인 유무 : :

것은

<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 클래스에 추가 pom.xml 파일에 추가 //stackoverflow.com/questions/21410317/using-gzip을 -compression-with-spring-boot-mvc-javaconfig-with-restful – aksappy

+0

@aksappy 예 했었습니다. 나는 그 해결책에서 대답 # 2에 대한 나의 해결책을 기반으로했다. –

+0

요청 헤더에는 HTTP 1.0을 나타내는 'keep-alive'가 있지만 참조 된 솔루션은'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 correct. server.xml이 없습니다. –

+0

동일한 문제가 있습니다 ... AWS Elastic Beanstalk (Tomcat 인스턴스)에 Spring Boot REST 응용 프로그램을 배포하므로 server.xml이 없습니다. 'Accept-Encoding : gzip, deflate'라고 지정해도 응답에는'Content-Encoding'이 표시되지 않습니다. 이 문제를 어떻게 해결할 수 있습니까? –

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 
+0

나는 @chimmi가 제안한 중단 점 접근법을 시도했고 모든 속성이 스프링 부트 컨테이너 (스크린 샷으로 원래 게시물을 업데이트했습니다)에 의해 읽혀 졌음을 보여 줬지만 어떻게 든 무시됩니다 ... –

1

스프링 부트 압축에 많은 어려움이 없었습니다. 간단한 솔루션은 ziplet 같은 타사 라이브러리를 사용하는 것입니다.

@Bean 
public Filter compressingFilter() { 
    return new CompressingFilter(); 
} 
관련 문제