pymongo 连接池和客户端请求 [英] pymongo connection pooling and client requests

查看:100
本文介绍了pymongo 连接池和客户端请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 pymongo 是线程安全的,并且有一个内置的连接池.

I know pymongo is thread safe and has an inbuilt connection pool.

在我正在开发的 Web 应用程序中,我正在针对每个请求创建一个新的连接实例.

In a web app that I am working on, I am creating a new connection instance on every request.

我的理解是,由于 pymongo 管理连接池,因此在每个请求上创建一个新连接并不是错误的方法,因为在请求结束时连接实例将被回收并将在后续请求中可用.

My understanding is that since pymongo manages the connection pool, it isn't wrong approach to create a new connection on each request, as at the end of the request the connection instance will be reclaimed and will be available on subsequent requests.

我在这里是否正确,还是应该只创建一个实例来跨多个请求使用?

Am I correct here, or should I just create a single instance to use across multiple requests?

推荐答案

错误的方法"取决于您的应用程序的架构.由于 pymongo 是线程安全的和自动连接池,单个共享连接或多个连接的实际使用将工作".但结果将取决于您期望的行为.文档对这两种情况都有评论.

The "wrong approach" depends upon the architecture of your application. With pymongo being thread-safe and automatic connection pooling, the actual use of a single shared connection, or multiple connections, is going to "work". But the results will depend on what you expect the behavior to be. The documentation comments on both cases.

如果您的应用程序是线程化的,从文档中可以看出,每个访问连接的线程都将获得自己的套接字.因此,无论您是创建单个共享连接,还是请求一个新的连接,都取决于您的请求是否是线程化的.

If your application is threaded, from the docs, each thread accessing a connection will get its own socket. So whether you create a single shared connection, or request a new one, it comes down to whether your requests are threaded or not.

使用 gevent 时,每个 greenlet 可以有一个套接字.这意味着您不必为每个请求创建一个真正的线程.请求可以是异步的,但仍然有自己的套接字.

When using gevent, you can have a socket per greenlet. This means you don't have to have a true thread per request. The requests can be async, and still get their own socket.

简而言之:

  • 如果您的 webapp 请求是线程化的,那么您访问新连接的方式并不重要.结果将是相同的(每个线程的套接字)
  • 如果您的 web 应用程序是通过 gevent 异步的,那么您访问新连接的方式并不重要.结果将是相同的.(每个 greenlet 的套接字)
  • 如果您的 web 应用程序是异步的,但不是通过 gevent,那么您必须考虑 最佳建议工作流程.

这篇关于pymongo 连接池和客户端请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆