Spring Boot响应压缩不起作用 [英] Spring boot response compression not working

查看:1886
本文介绍了Spring Boot响应压缩不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些很大的javascript捆绑文件,大约1MB. 我正在尝试使用yml文件中的以下应用程序属性打开响应压缩:

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:

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.

请求标头:

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

响应中没有内容编码标头.

There's no content encoding header in the response.

我正在使用Spring Boot版本1.3.5.RELEASE

I'm using spring boot version 1.3.5.RELEASE

我想念什么?

===编辑4 === 我打算创建一个独立的应用程序,以进一步调查为何内容压缩属性不起作用. 但是突然间它开始工作了,我没有在配置方面进行任何更改,没有更改POM文件,也没有更改application.yml文件.因此,我不知道是什么改变了它才能起作用...

=== 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...

===编辑3 === 进一步遵循@chimmi的建议.我已在建议的位置放置了断点.看起来对静态资源(js文件)的请求从未在这些断点处停止.只有其余的API请求可以.对于这些请求,由于某种原因,内容长度为零,这会导致内容压缩被跳过.

===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.

===编辑2 === 感谢@chimmi的建议,我在o.s.b.a.w.ServerProperties的第180行处设置了一个断点,它显示了所有属性都已设置,但是服务器不知何故不接受该设置...:(

===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... :(

===编辑1 ===

不确定是否重要,但是我将应用程序主代码和配置代码粘贴到此处:

not sure if it matters, but I'm pasting my application main and configuration code here:

Application.java:

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
    }
}

推荐答案

也许问题出在YAML配置上. 如果您使用启动器",则将通过spring-boot-starter自动提供SnakeYAML.如果不这样做,则必须在application.properties中使用属性约定. 使用YAML而不是属性

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

在您的yml文件中尝试以下操作:

Try with this in your yml file:

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

这篇关于Spring Boot响应压缩不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆