springboot 长连接 keepalive 记录

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.youkuaiyun.com/download/zjh1n795/16135081

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值