apache连接池机制讨论

apache连接池的连接有效性

server一般会配置keep-alive超时时间,过了这个时间还没新请求到来,则关闭连接。客户端从连接池里拿出连接时,会检查一下连接是否已关闭,如已关闭,会丢弃掉该连接,并尝试从连接池再拿一个新的连接,代码机制在AbstractConnPool.lease方法里:

java 复制代码
public Future<E> lease(final T route, final Object state, final FutureCallback<E> callback) {
        Args.notNull(route, "Route");
        Asserts.check(!this.isShutDown, "Connection pool shut down");
        return new Future<E>() {
            ...
            public E get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
                while(true) {
                    synchronized(this) {
                        PoolEntry var10000;
                        try {
                            E entry = (PoolEntry)this.entryRef.get();
                            if (entry != null) {
                                var10000 = entry;
                            } else {
                                ...
                               // 从连接池租借一个连接
                                E leasedEntry = AbstractConnPool.this.getPoolEntryBlocking(route, state, timeout, timeUnit, this);
                                // 如果租借的连接未关闭,就用该连接返回之
                                if (AbstractConnPool.this.validateAfterInactivity <= 0 || leasedEntry.getUpdated() + (long)AbstractConnPool.this.validateAfterInactivity > System.currentTimeMillis() || AbstractConnPool.this.validate(leasedEntry)) {
                                    if (!this.done.compareAndSet(false, true)) {
                                        AbstractConnPool.this.release(leasedEntry, true);
                                        throw new ExecutionException(AbstractConnPool.operationAborted());
                                    }

                                    this.entryRef.set(leasedEntry);
                                    this.done.set(true);
                                    AbstractConnPool.this.onLease(leasedEntry);
                                    if (callback != null) {
                                        callback.completed(leasedEntry);
                                    }

                                    var10000 = leasedEntry;
                                    return var10000;
                                }
							// 租借的连接已关闭,关闭该连接,并回到while循环开始,继续调用getPoolEntryBlocking获得新的连接,若池子里没有连接,创建一个新连接。
                                leasedEntry.close();
                                AbstractConnPool.this.release(leasedEntry, false);
                                continue;
                            }
                        } catch (IOException var8) {
                           ...
                        }

                        return var10000;
                    }
                }
            }
        };
    }

AbstractConnPool.this.validate会调用connection的isStale方法:

java 复制代码
//CPool.java
protected boolean validate(CPoolEntry entry) {
        return !((ManagedHttpClientConnection)entry.getConnection()).isStale();
    }

那么一个连接是如何判定不新鲜(stale)的呢?逻辑如下:

java 复制代码
//BHttpConnectionBase.java
public boolean isStale() {
        if (!this.isOpen()) {
            return true;
        } else {
            try {
                int bytesRead = this.fillInputBuffer(1);
                return bytesRead < 0;
            } catch (SocketTimeoutException var2) {
                return false;
            } catch (IOException var3) {
                return true;
            }
        }
    }

fillInputBuffer方法会尝试从socket里读取字节,返回值为读取的字节数,若返回-1,说明连接已关闭。

顺带说一下,实测发现,isStale的判定对于server端正常或异常关闭连接的情况,都能检测到

各web服务器的keep-alive策略配置

很显然,一个用于生产的web服务器是要配置keep-alive超时的,毕竟机器的IO连接资源有限,万一大量的长连接被占用,新来的请求将得不到服务。

fastAPI可以在启动时指定keepalive的超时时间,像这样:

python 复制代码
app = FastAPI()

@app.get("/test")
async def root():
    return "Hello fastapi"

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8002, timeout_keep_alive=600)

这里我们指定600s,默认keepalive超时是5s,即5s没有请求则关闭连接

tomcat的keep-alive策略配置在server.xml里,除了keepAliveTimeout之外,还有maxKeepAliveRequests选项,意思是服务多少个请求后就关闭连接,例如下面的例子,在服务5个请求后关闭连接:

xml 复制代码
<Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               maxThreads="1000"

               acceptCount="100"

               redirectPort="8443"

               URIEncoding="UTF-8"

               maxKeepAliveRequests="5"/>

两个参数的含义如下:

复制代码
keepAliveTimeout:
The number of milliseconds Tomcat will wait for a subsequent request before closing the connection

maxKeepAliveRequests:
Maximum number of Keep-Alive requests to honor per connection
相关推荐
秋916 分钟前
Go语言(Golang)开发工程师全景解析:岗位职责·语言优势与使用场景·各城市薪资·发展前景·高考志愿填报(2026版)
开发语言·golang·高考
无风听海35 分钟前
多租户系统中的 OIDC:Discovery 端点与联合登录的深度实践
后端·python·flask
CTA终结者1 小时前
期货量化主力换月程序怎么移仓:天勤 underlying_symbol 与任务切换
python·区块链
huangdong_1 小时前
1688商品图片采集技术解析:登录态处理与SKU图自动分类
开发语言
马士兵教育1 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
chase_my_dream1 小时前
C++ + SLAM 高频面试问题整理
开发语言·c++·面试
KaMeidebaby2 小时前
卡梅德生物技术快报|纯化重组蛋白实操详解
人工智能·python·tcp/ip·算法·机器学习
Cloud_Shy6182 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 30 - 32)
开发语言·人工智能·笔记·python·学习方法
天佑木枫2 小时前
15天Python入门系列 · 序
开发语言·python
happylifetree2 小时前
Python017-第二章15.数据容器-dict常用操作
python