如何在 docker 图像中禁用 Spring Boot 应用程序中的 Keep alive

How to disable Keep alive in SpringBoot application in docker image

我们有一个采用以下技术的 Web 应用程序:Java、SpringBoot、Docker、微服务、Jhipster。 前端容器的端口号是 80.

我正在尝试禁用前端微服务的保持活动选项,因为 SSO 身份验证服务器要求将此参数设置为 false。

我尝试用 maven 创建前端容器:mvn -Pqpm,no-liquibase -Dhttp.keepAlive=false clean verify jib:dockerBuild

我还尝试在前端容器的 pom.xml 中禁用:

<http.keepAlive>false</http.keepAlive>
<https.keepAlive>false</https.keepAlive>

但是当我发送 http 请求时,keep-alive 选项仍然启用:

Connecting to qwerty.xyz|10.10.219.200|:80... connected.
HTTP request sent, awaiting response... 
  HTTP/1.1 200 OK
  Date: Mon, 06 Apr 2020 21:14:50 GMT
  Server: Apache
  Last-Modified: Fri, 21 Oct 2016 08:42:15 GMT
  ETag: "4107-84-53f5c04e1c7c0"
  Accept-Ranges: bytes
  Content-Length: 132
  Cache-Control: max-age=0, no-store
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Content-Type: text/html
Length: 132 [text/html]
Saving to: `/dev/null'

     0K                                                       100% 15.7M=0s

2020-04-06 23:14:50 (15.7 MB/s) - `/dev/null' saved [132/132]

我的 Springboot 配置:

<!-- Dependency versions -->
<jhipster-dependencies.version>3.0.1</jhipster-dependencies.version>
<!-- The spring-boot version should match the one managed by
https://mvnrepository.com/artifact/io.github.jhipster/jhipster-dependencies/${jhipster-dependencies.version} -->
<spring-boot.version>2.1.4.RELEASE</spring-boot.version>

你能帮我禁用它吗?

我终于找到了解决办法。我们这样做的方法是实现一个过滤器并将这个过滤器添加到 SecurityConfig.config 方法。

    KeepAliveFilter.java

    public class KeepAliveFilter implements Filter {
        public void init(final FilterConfig filterConfig) { }

        public void destroy() { }

        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            final HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Connection", "close");
            chain.doFilter(request, response);
        }
    }

    SecurityConfiguration.java

    private final KeepAliveFilter keepAliveFilter;

    public SecurityConfiguration(final KeepAliveFilter keepAliveFilter, ...) 
    {
        this.keepAliveFilter = keepAliveFilter;
    ...
    // other property
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .and()
            .addFilterBefore(corsFilter, CsrfFilter.class)
            .addFilterBefore(keepAliveFilter, CsrfFilter.class)
            ;
    }

您可以在 spring application.properties 文件中禁用它,对于我的情况,我使用的是 yaml 配置文件,所以在我的 application.yml 我做的文件:

server:
  undertow:
    always-set-keep-alive: false