如何在 Spring 启动时禁用 Tomcat 的 permessage-deflate WebSocket 压缩?

How Can I Disable Tomcat's permessage-deflate WebSocket Compression in Spring Boot?

我有一个 Spring 引导服务器,我希望它能够与无法或不愿处理 permessage-deflate 压缩消息的 websocket 客户端通信。我从关于该主题的这两个类似问题(链接如下)中知道我可以添加 VM 参数 -Dorg.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS=true 来禁用 Tomcat 的默认 deflate 压缩。

但是,我计划制作一个程序,以便其他人可以 运行 它,并且不得不强迫人们记住总是包括一个特定的 VM 参数只是为了改变一个设置似乎非常粗暴。

是否有一些替代方法可以禁用 Tomcat 的 websocket 压缩,它不需要用户在 运行 时指定 VM 参数,也许使用 Spring 的 Java 配置或自定义 websocket 握手拦截器?

您不仅可以使用 JVM 参数设置属性,还可以使用 System.setProperty 以编程方式设置属性,如下所示:

System.setProperty("org.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS",String.valueOf(true));

如果您使用嵌入式 tomcat 将项目导出到 JAR 文件,您可以在执行 SpringApplication.run:[=16= 之前在 main 中 运行 它]

public static void main(String[] args) {
    System.setProperty("org.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS",String.valueOf(true));
    SpringApplication.run(YourApplicationClass.class,args);
}

如果您将应用程序打包到 WAR 文件中,您可以尝试以下操作:

@SpringBootApplication
public class YourApplicationClass extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        System.setProperty("org.apache.tomcat.websocket.DISABLE_BUILTIN_EXTENSIONS",String.valueOf(true));
        return application.sources(YourApplicationClass.class);
    } 
}