maven引入依赖

<dependency>
 <groupId>org.jodd</groupId>
 <artifactId>jodd-http</artifactId>
 <version>5.1.4</version>
</dependency>

设置keepalive java配置:

@Configuration
public class WebServerConfiguration implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        //使用对应工厂类提供给我们的接口定制化我们的tomcat connector
        ((TomcatServletWebServerFactory) factory).addConnectorCustomizers(new TomcatConnectorCustomizer() {
            @Override
            public void customize(Connector connector) {
                Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
                //定制KeepAliveTimeout,设置10秒内没有请求则服务器自动断开keepalive连接
                protocol.setKeepAliveTimeout(10000);
                //当客户端发送超过5个请求则自动断开keepalive连接
                protocol.setMaxKeepAliveRequests(5);
            }
        });
    }
}

测试代码:
 

@Slf4j
public class TestHttp11 {

    public static void main(String[] args) throws Exception {
        HttpResponse response = null;
        for (int i = 0; i < 12; i++) {

            response = http11(i, response, i == (10 - 1));
            Thread.sleep(9000);
            if (i > 1) {
                Thread.sleep(3000);
            }
        }
    }

    /*
    服务端设置最大请求次数(MaxKeepAliveRequests)为5,超时时间(KeepAliveTimeout)为10秒
    1、请求10次,每次间隔1秒
        抓包发现5次后服务端返回  Connection: close
        第6次请求无异常 创建新的连接
    2、请求3次,每次间隔12秒
        第二次请求后异常报错
    3、请求3次,每次间隔9秒
        无异常
    4、请求6次,1-2次间隔9秒,2次以后间隔12秒
        第四次后异常

    <dependency>
            <groupId>org.jodd</groupId>
            <artifactId>jodd-http</artifactId>
            <version>5.1.4</version>
        </dependency>
     */
    public static HttpResponse http11(int num, HttpResponse response, boolean last) throws UnsupportedEncodingException {
        HttpRequest request = HttpRequest.get("http://127.0.0.1:8080/test/http11?num=" + num);
        if (response == null) {
            response = request.connectionKeepAlive(true).send();
        } else {
            if (!last) {
                response = request.keepAlive(response, true).send();
            } else {
                response = request.keepAlive(response, false).send();
            }
        }
        String info = new String(response.body().getBytes("iso8859-1"), "utf-8");
        System.out.println(info);
        return response;
    }

}

源码下载:
https://download.csdn.net/download/zjh1n795/16135081

 

参考:
https://blog.csdn.net/weixin_41657493/article/details/90819987
https://blog.51cto.com/15015181/2556402?source=drt

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐