我在 Django 的 views.py 中有一个 db = pymongo.Connection()
调用,用于简单的 MongoDB 连接以存储一些简单的统计信息。
使其自动支持 MongoDB 连接池的最佳做法是什么?
我需要把 end_request()
代码放在哪里?
连接时如何选择max_pool_size
参数?
最佳答案
How does connection pooling work in PyMongo?
Every Connection instance has built-in connection pooling. By default, each thread gets its own socket reserved on its first operation. Those sockets are held until end_request() is called by that thread.
Calling end_request() allows the socket to be returned to the pool, and to be used by other threads instead of creating a new socket. Judicious use of this method is important for applications with many threads or with long running threads that make few calls to PyMongo operations.
Alternatively, a Connection created with auto_start_request=False will share sockets (safely) among all threads.
我认为这取决于您拥有的应用程序类型以及请求将保持连接多长时间。调用 end_request
的想法有助于长时间运行的请求长时间保持套接字并导致创建许多套接字。如果单个请求可以在不再需要连接时释放连接,则套接字可以重新用于其他请求。
如果它们是快速请求,那么我相信 auto_start_request=False
可以通过重用套接字来工作。
确保连接一直使用相同的套接字意味着读取的一致性。想想如果您进行了查询但它被延迟了,然后立即进行了另一个查询并且它使用了不同的套接字。此套接字设法在前一个套接字之前响应。你会有不一致的数据,因为它不反射(reflect)以前的写入。
关于django - django + PyMongo 池化的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11498734/