了解Python中的数据库连接池

6

我不确定我是否理解了Python中DB连接池的用例(例如:psycopg2.pool和mysql.connector.pooling)。在Python中,由于GIL的存在,通常使用多进程而不是多线程方法来实现并行。在多进程情况下,这些连接池似乎没有什么用处,因为每个进程都会初始化自己的连接池,并且一次只能运行一个线程。这是正确的吗?如果使用多个进程时没有共享DB连接池的策略,那么连接池的有用性是否仅限于多线程Python应用程序,或者是否还有其他场景可以使用它们?

1个回答

7

Keith,

你正在正确的轨道上。正如在 S.O 的帖子 "Accessing a MySQL connection pool from Python multiprocessing" 中提到的那样:

Making a seperate pool for each process is redundant and opens up way
too many connections.

请查看其他S.O帖子,“Python中最佳的数据库连接池解决方案是什么?”,其中包含Python中的示例池解决方案。该帖子还讨论了如果您的应用程序变成多线程时,数据库池的限制:

Making your own connection pool is a BAD idea if your app ever decides to start using 
multi-threading. Making a connection pool for a multi-threaded application is much 
more complicated than one for a single-threaded application. You can use something 
like PySQLPool in that case.

在Python中实现数据库连接池,如"应用程序与数据库驻留的连接池"所述,如果您的数据库支持它,则最佳实现应该包括:

Let connection pool be maintained and managed by database itself 
(example: Oracle's DRCP) and calling modules just ask connections from the connection 
broker described by Oracle DRCP.

如果您有任何问题,请告诉我!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接