Rails数据库连接池如何工作 [英] How rails database connection pool works

查看:128
本文介绍了Rails数据库连接池如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Rails数据库连接池的概念.在Rails应用程序中,我将池大小定义为5.

I am learning rails database connection pool concept. In rails application I have defined pool size of 5.

我对连接池大小的理解如下.

my understanding about connection pool size is as below.

  1. 当服务器启动时,rails会自动在database.yml文件中创建n个连接.在我的情况下,由于池大小为5,它将创建5个连接.

  1. When server start rails automatically creates n number of connection defined in the database.yml file. In my case it will create 5 connection since pool size is 5.

在每个http请求上,如果需要访问数据库,那么Rails将使用来自连接池的可用连接来服务该请求.

On every http request if there is need to access database then rails will use available connection from the connection pool to serve the request.

但是我的问题是,如果我一次命中1000个请求,那么大多数请求将无法访问数据库连接,因为我的连接池大小仅为5.

But my question is if I hit 1000 request at a time then most of the request will not get access to database connection because my connection pool size is only 5.

我对Rails连接池的理解是否正确?

Is my above understanding about rails connection pool is right??

谢谢

推荐答案

目的:
数据库连接不是线程安全的;因此ActiveRecord为每个线程使用单独的数据库连接.

Purpose:
Database connections are not thread safe; so ActiveRecord uses separate database connection for each thread.

限制因素:
数据库连接总数受您使用的数据库服务器的限制(例如Posgres:默认通常是100或更小),具体取决于应用服务器的配置(可用进程/线程数)和Active Record的配置:

Limiting factor:
Total database connections is limited by the database server you use (e.g Posgres: default is typically 100 or lesser), by your app server's configuration (number of processes/threads available) and Active Record's configuration : Connection Pool defaults to 5 .

泳池大小:
Active Record的池大小适用于单个进程.线程使用该池中的连接,然后自动释放它. (除非您自己生成线程,否则必须手动释放它).如果您的应用程序在多个进程上运行,则每个进程将有5个数据库连接.如果您的服务器同时受到1000个请求的攻击,它将在这些连接中分配这些请求,当服务器连接已满时,其余的请求将等待轮到它们.

Pool size:
Active Record's pool size is for a single process. A thread uses a connection from this pool and releases it automatically afterwards. (unless you spawn a thread yourself, then you'll have to manually release it). If your application is running on multiple processes, you will have 5 database connections for each of them. If your server is hit by 1000 requests concurrently, it will distribute the requests among these connections, when it gets full, rest of the requests wait for their turn.

更多信息,请访问:
https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool. html

Read more at:
https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html

这篇关于Rails数据库连接池如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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