简体   繁体   English

如何使用psycopg和gevent汇集连接?

[英]How can I pool connections using psycopg and gevent?

The psycopg docs state: "Psycopg connections are not green thread safe and can't be used concurrently by different green threads. Trying to execute more than one command at time using one cursor per thread will result in an error (or a deadlock on versions before 2.4.2). Therefore, programmers are advised to either avoid sharing connections between coroutines or to use a library-friendly lock to synchronize shared connections, eg for pooling." psycopg文档声明:“Psycopg连接不是绿色线程安全的,并且不能由不同的绿色线程同时使用。尝试每个线程使用一个游标执行多个命令将导致错误(或版本上的死锁因此,建议程序员避免在协同程序之间共享连接或使用库友好的锁来同步共享连接,例如用于池化。

I can't find an implementation of pool that is green thread safe - are there any out there? 我找不到绿色线程安全的池的实现 - 那里有没有?

I assume you know gevent-psycopg2 module, which makes psycopg greenlet-friendly. 我假设你知道gevent-psycopg2模块,它使psycopg greenlet友好。

Looking for connection pooling solution I've tried 2 solutions: 寻找连接池解决方案我尝试了2个解决方案:

  • SQLALchemy - it seems to work properly with monkey-patched threads and gevent-psycopg2 . SQLALchemy - 它似乎与猴子修补的线程和gevent-psycopg2一起正常工作。 The QueuePool class uses threading module internally for locking, monkey patching is thus necessary, even though gevent-psycopg2 makes psycopg2 green. QueuePool类在内部使用threading模块进行锁定,因此需要进行猴子修补,即使gevent-psycopg2使psycopg2 gevent-psycopg2绿色。

  • there's a psycopg2 connection pooling example in gevent examples gevent示例中有一个psycopg2 连接池示例

I've tried both solutions, but not at production load - so I can't say about their robustness yet. 我已经尝试了两种解决方案,但没有尝试生产负载 - 所以我还不能说它们的稳健性。

If you call gevent.monkey.patch_thread() you should be able to use psycopg2.pool.ThreadedConnectionPool . 如果你调用gevent.monkey.patch_thread()你应该可以使用psycopg2.pool.ThreadedConnectionPool

这是一个很好的池(不只是示例,但在生产中使用): psycopg2_pool.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM