Druid连接池的keepAlive
时间: 2023-12-18 07:27:47 浏览: 240
Druid连接池的keepAlive是指连接池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作。keepAlive操作会向数据库发送一个测试SQL语句,以确保连接仍然有效。如果连接无效,则会将其从连接池中删除。如果连接有效,则会将其放回连接池中以供后续使用。
以下是一个使用Druid连接池的Python代码示例,其中包括了keepAlive的配置:
```python
import pymysql
from sqlalchemy import create_engine
from sqlalchemy.pool import QueuePool
from DBUtils import PooledDB
import time
# 创建连接池
pool = PooledDB(
creator=pymysql,
maxconnections=6,
mincached=2,
maxcached=5,
blocking=True,
maxusage=None,
setsession=[],
ping=0,
host='localhost',
port=3306,
user='root',
password='123456',
database='test',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor,
connect_timeout=10,
read_timeout=10,
write_timeout=10,
keepalive=600 # keepAlive的配置,单位为秒
)
# 从连接池中获取连接
conn = pool.connection()
# 使用连接进行数据库操作
engine = create_engine('mysql+pymysql://', creator=pool.getconn, poolclass=QueuePool, pool_size=6)
with engine.connect() as conn:
result = conn.execute('SELECT * FROM test_table')
for row in result:
print(row)
# 将连接放回连接池中
pool.putconn(conn)
```
阅读全文