我不确定我是否理解 Python 中数据库连接池(例如:psycopg2.pool 和 mysql.connector.pooling)的用例。在我看来,并行性通常是在 python 中使用多进程而不是多线程方法实现的,因为 GIL,并且在多进程的情况下,这些池不是很有用,因为每个进程都会初始化自己的池并且一次只会运行一个线程。这样对吗?在使用多个进程时是否有任何共享数据库连接池的策略,如果没有,池的用处是否仅限于多线程 python 应用程序,或者是否有其他场景可以使用它们?
最佳答案
基思,
您走在正确的轨道上。如 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 帖子“What is the best solution for database connection pooling in python?”,它包含一个 python 中的示例池解决方案。如果您的应用程序成为多线程,这篇文章还讨论了 db-pooling 的局限性:
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 中实现数据库池而言,如“Application vs Database Resident Connection Pool”中所述,如果您的数据库支持它,最好的实现包括:
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.
如有任何问题,请告诉我!
关于python - 理解 python 中的数据库连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26266842/