是否有任何理由使用与ActiveRecord的数据库连接池? [英] Is there any reason to use a database connection pool with ActiveRecord?

查看:325
本文介绍了是否有任何理由使用与ActiveRecord的数据库连接池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使用外部连接池的好处是什么?

我听说大多数其他应用程序将打开每个工作单元的连接。在Rails中,例如,我认为这意味着每个请求可以打开一个新的连接。我假设一个连接池会做到这一点。

我能想到的唯一的好处是,它可以让你有1000前端流程,而无需运行1000 Postgres处理。

是否还有其他的好处?

解决方案

Rails有建于连接池:

  
      
  1. 只需使用ActiveRecord :: Base.connection来与活动记录2.1和更早版本(pre-连接池)。最后,当你连接(S)就大功告成了,并希望它返回到池中,您拨打的ActiveRecord :: Base.clear_active_connections!这将是活动记录的默认行为与行动宝盒的请求处理周期结合使用时。
  2.   
  3. 在手动检查从用ActiveRecord :: Base.connection_pool.checkout池中的连接。您有责任在调用的ActiveRecord :: Base.connection_pool.checkin(连接)完成返回此连接池。
  4.   
  5. 使用的ActiveRecord :: Base.connection_pool.with_connection(安培;块),其中获得一个连接,得到它作为唯一的参数来将挡,并将其返回到块完成后,池
  6.   

这已经可以从版本2.2 。你会看到一个在参数的的database.yml 控制它:

  

:数字,表示连接池的大小(默认5)

我不认为会有什么意义分层它下面的另一个池系统,它甚至可能混淆AR的池,如果你尝试过了。

What are the benefits to using an external connection pool?

I've heard that most other applications will open up a connection for each unit of work. In Rails, for example, I'd take that to mean that each request could open a new connection. I'm assuming a connection pool would make that possible.

The only benefit I can think of is that it allows you to have 1,000 frontend processes without having 1,000 postgres processes running.

Are there any other benefits?

解决方案

Rails has connection pooling built in:

  1. Simply use ActiveRecord::Base.connection as with Active Record 2.1 and earlier (pre-connection-pooling). Eventually, when you’re done with the connection(s) and wish it to be returned to the pool, you call ActiveRecord::Base.clear_active_connections!. This will be the default behavior for Active Record when used in conjunction with Action Pack’s request handling cycle.
  2. Manually check out a connection from the pool with ActiveRecord::Base.connection_pool.checkout. You are responsible for returning this connection to the pool when finished by calling ActiveRecord::Base.connection_pool.checkin(connection).
  3. Use ActiveRecord::Base.connection_pool.with_connection(&block), which obtains a connection, yields it as the sole argument to the block, and returns it to the pool after the block completes.

This has been available since version 2.2. You'll see a pool parameter in your database.yml for controlling it:

pool: number indicating size of connection pool (default 5)

I don't think there would be much point in layering another pooling system underneath it and it could even confuse AR's pooling if you tried it.

这篇关于是否有任何理由使用与ActiveRecord的数据库连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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