sequenceize — размер пула соединений

сейчас я читаю статью на http://docs.sequelizejs.com/manual/installation/getting-started.html

и не могу понять эти предложения, написанные ниже.

Если вы подключаетесь к базе данных из нескольких процессов, вам придется создать один экземпляр для каждого процесса, но каждый экземпляр должен иметь максимальный размер пула соединений, равный "максимальному размеру пула соединений, разделенному по количеству экземпляров". Итак, если вы хотите, чтобы максимальный размер пула соединений составлял 90, и у вас было 3 рабочих процесса, каждый экземпляр процесса должен иметь максимальный размер пула соединений, равный 30.

pool: {
  max: 5,
  min: 0,
  idle: 10000
}

какой размер пула соединений? это значит макс?

теперь я понимаю такой пул соединений. если «max» равно 5, и 3 пользователя хотят получить доступ к БД, каждому пользователю выделяется 3 соединения.

и если 6 пользователей хотят получить БД, все 5 подключений выделяются отдельному пользователю, и, поскольку есть только 5 подключений, 6-й пользователь должен ждать.

поэтому я не могу понять

каждый экземпляр должен иметь максимальный размер пула соединений, равный «максимальному размеру пула соединений, деленному на количество экземпляров».

кто-нибудь может объяснить об этом?


person jwkoo    schedule 10.09.2017    source источник


Ответы (2)


Это очень широкий вопрос, но вот очень широкий обзор

Всякий раз, когда мы подключаемся к серверу БД, он фактически создает новый процесс для выполнения этого запроса. Как вы понимаете, это дорого. Таким образом, пул позволяет нам поддерживать количество активных процессов на сервере БД. max означает, что независимо от того, сколько запросов получит ваше приложение (узел), оно не откроет новый процесс с сервером БД.

и если 6 пользователей хотят получить БД, все 5 подключений выделяются отдельному пользователю, и, поскольку есть только 5 подключений, 6-й пользователь должен ждать.

В приведенном выше случае только 5 параллельных запросов могут выполняться с сервером БД (а не с сервером приложений).

Вот хорошая ссылка для чтения

person AbhinavD    schedule 29.05.2018
comment
признателен за ответ на этот старый вопрос. Таким образом, размер пула — это способ сэкономить на разветвлении нового процесса каждый раз. В документе sequenceize есть код руководства для максимального размера пула соединений: 5, но в любом случае это код руководства. так какой максимальный размер пула подходит для приложения среднего размера? (не имея в виду большие сервисы, такие как facebook и т. д.), может быть, 100? - person jwkoo; 29.05.2018
comment
даже если я использую размер пула соединений, если я установлю размер пула соединений для очень большого числа и меньшего количества пользователей, будет разница в том, устанавливаю ли размер пула или нет. @AbhinavD - person jwkoo; 29.05.2018
comment
Очень сложно сказать, какое число является правильным. Зависит от соотношения запросов на чтение/запись (поскольку запись блокирует строку), вашего оборудования и т. д. Как упоминалось в документе, которым я поделился, существует the "Knee", за пределами которого производительность БД будет уменьшаться, если вы увеличиваете размер пула. Кроме того, когда вы устанавливаете db, сама конфигурация db сообщает ему, какой максимум он может выдержать. Вам придется изменить это и размер вашего пула приложений, чтобы заставить его работать. - person AbhinavD; 29.05.2018
comment
большое спасибо! можете ли вы проверить мой последний комментарий, правильно ли я понял ваши слова в предыдущем вопросе (продолжение)? - person jwkoo; 29.05.2018
comment
Я думаю, ты понял. Поскольку я никогда не использую sync, я также всегда создаю внешний ключ в модели. - person AbhinavD; 29.05.2018

Вот пример, демонстрирующий действие параметров pool.max и pool.idle.

Окружающая среда:

  • "sequelize": "^5.21.3"
  • node: v12.16.1
  • PostgreSQL: 9.6

Код клиента:

db.ts:

const sequelize = new Sequelize({
  dialect: 'postgres',
  host: envVars.POSTGRES_HOST,
  username: envVars.POSTGRES_USER,
  password: envVars.POSTGRES_PASSWORD,
  database: envVars.POSTGRES_DB,
  port: Number.parseInt(envVars.POSTGRES_PORT, 10),
  define: {
    freezeTableName: true,
    timestamps: false,
  },
  pool: {
    max: 5,
    min: 0,
    idle: 10 * 1000,
  },
});
export { sequelize };

pool_test.ts:

import { sequelize } from '../../db';

for (let i = 0; i < 100; i++) {
  sequelize.query('select pg_sleep(1);');
}

Запустите сервер PostgreSQL с помощью док-контейнера:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
3c9c0fd1bf53        postgres:9.6        "docker-entrypoint.s…"   5 months ago        Up 27 hours         0.0.0.0:5430->5432/tcp   node-sequelize-examples_pg_1

Запустите тестовый код:

DEBUG=sequelize* npx ts-node ./pool_test.ts

Отчет об ошибках:

  sequelize:pool pool created with max/min: 5/0, no replication +0ms
  sequelize:connection:pg connection acquired +0ms
  sequelize:connection:pg connection acquired +38ms
  sequelize:connection:pg connection acquired +3ms
  sequelize:connection:pg connection acquired +0ms
  sequelize:connection:pg connection acquired +1ms
  sequelize:connection:pg connection acquired +1ms
  sequelize:pool connection acquired +97ms
  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms
Executing (default): select pg_sleep(1);
  sequelize:pool connection acquired +2ms
  sequelize:pool connection acquired +0ms
  sequelize:pool connection acquired +0ms
  sequelize:pool connection acquired +0ms
  sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms
Executing (default): select pg_sleep(1);
  sequelize:sql:pg Executing (default): select pg_sleep(1); +2ms
Executing (default): select pg_sleep(1);
  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms
Executing (default): select pg_sleep(1);
  sequelize:sql:pg Executing (default): select pg_sleep(1); +0ms
Executing (default): select pg_sleep(1);
  sequelize:sql:pg Executed (default): select pg_sleep(1); +1s
  sequelize:pool connection released +1s
  sequelize:pool connection acquired +1ms
  sequelize:sql:pg Executed (default): select pg_sleep(1); +2ms
  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms
  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms
  sequelize:sql:pg Executed (default): select pg_sleep(1); +0ms
  sequelize:sql:pg Executing (default): select pg_sleep(1); +1ms
Executing (default): select pg_sleep(1);
  sequelize:pool connection released +1ms
  sequelize:pool connection released +0ms
  sequelize:pool connection released +0ms
  sequelize:pool connection released +0ms
  sequelize:pool connection acquired +1ms
  sequelize:pool connection acquired +0ms
  sequelize:pool connection acquired +0ms
  sequelize:pool connection acquired +0ms

Заходим в докер-контейнер, проверяем процесс подключения:

root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:51:34 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
postgres 14335  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45704) SELECT
postgres 14336  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45706) SELECT
postgres 14337  0.0  0.5 288384 11252 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45708) SELECT
postgres 14338  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45710) SELECT
postgres 14339  0.0  0.5 288384 11248 ?        Ss   09:51   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45712) SELECT
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle

Как видите, процессов подключения 5(pool.max).

После обработки соединения IDLE 10(pool.idle) секунд. Процессы подключения будут уничтожены.

root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:53:48 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
postgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle
postgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle
postgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) SELECT
postgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle
postgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) SELECT
root     14440  0.0  0.0  12784   972 pts/3    S+   09:53   0:00 grep postgres: testuser
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle
root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:53:49 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
postgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle
postgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle
postgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle
postgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle
postgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle
root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:53:55 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
postgres 14352  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45716) idle
postgres 14353  0.0  0.5 288384 11252 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45718) idle
postgres 14354  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45720) idle
postgres 14355  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45722) idle
postgres 14356  0.0  0.5 288384 11248 ?        Ss   09:53   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45724) idle
root     14446  0.0  0.0  12784   932 pts/3    S+   09:53   0:00 grep postgres: testuser
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle
root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:53:58 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
root     14449  0.0  0.0  12784   940 pts/3    S+   09:53   0:00 grep postgres: testuser
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle

журналы отладки клиента:

...
  sequelize:pool connection released +25ms
  sequelize:pool connection destroy +10s
  sequelize:pool connection destroy +0ms
  sequelize:pool connection destroy +0ms
  sequelize:pool connection destroy +0ms
  sequelize:pool connection destroy +1ms

Если вы измените pool.max на 10, проверьте количество процессов подключения:

root@3c9c0fd1bf53:/# date '+%A %W %Y %X' && ps aux | grep "postgres: testuser"
Thursday 31 2020 09:56:51 AM
postgres 13615  0.0  0.7 289496 16064 ?        Ss   08:29   0:00 postgres: testuser node-sequelize-examples [local] idle
postgres 14457  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45728) SELECT
postgres 14458  0.0  0.5 288384 11252 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45730) SELECT
postgres 14459  0.0  0.5 288384 11252 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45732) SELECT
postgres 14460  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45734) SELECT
postgres 14461  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45736) SELECT
postgres 14462  0.0  0.5 288384 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45738) SELECT
postgres 14463  0.0  0.5 288384 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45740) SELECT
postgres 14464  0.0  0.5 288388 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45742) SELECT
postgres 14465  0.0  0.5 288388 11244 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45744) SELECT
postgres 14466  0.0  0.5 288388 11248 ?        Ss   09:56   0:00 postgres: testuser node-sequelize-examples 172.18.0.1(45746) SELECT
root     14472  0.0  0.0  12784   944 pts/3    S+   09:56   0:00 grep postgres: testuser
postgres 86437  0.0  0.6 288804 13704 ?        Ss   00:57   0:00 postgres: testuser node-sequelize-examples [local] idle
person slideshowp2    schedule 06.08.2020