重庆思庄Oracle、Redhat认证学习论坛

标题: PYTHON模拟到PG最大连接数 [打印本页]

作者: 郑全    时间: 2023-12-10 19:50
标题: PYTHON模拟到PG最大连接数
1.语句

[postgres@eulersvr ~]$ cat conn_test.py
import psycopg2
import threading

# 连接数据库的配置信息
db_config = {
    'host': '192.168.0.38',
    'port': 5432,
    'database': 'postgres',
    'user': 'postgres',
    'password': 'postgres'
}

# 连接函数
def connect_to_database():
    # 建立连接
    conn = psycopg2.connect(**db_config)

    # 执行操作
    cursor = conn.cursor()
    cursor.execute("SELECT pg_sleep(10)")

    # 关闭游标
    cursor.close()

# 并发连接数,这个值可以调整
concurrent_connections = 100

# 创建连接线程
threads = []
for _ in range(concurrent_connections):
    t = threading.Thread(target=connect_to_database)
    threads.append(t)
    t.start()

# 等待所有线程完成
for t in threads:

    t.join()

2.参数:
  postgres=# show max_connections;
max_connections
-----------------
100
(1 row)

3.执行

[postgres@eulersvr ~]$ python3 conn_test.py
Exception in thread Thread-94 (connect_to_database):
Traceback (most recent call last):
  File "/usr/lib64/python3.11/threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "/usr/lib64/python3.11/threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "/home/postgres/conn_test.py", line 16, in connect_to_database
    conn = psycopg2.connect(**db_config)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
psycopg2.OperationalError: connection to server at "192.168.0.38", port 5432 failed: FATAL:  sorry, too many clients already










欢迎光临 重庆思庄Oracle、Redhat认证学习论坛 (http://bbs.cqsztech.com/) Powered by Discuz! X3.2