DBResolver добавляет поддержку нескольких баз данных для GORM, поддерживаются следующие функции:
- Несколько источников, реплики
- Разделение чтения/записи
- Автоматическое переключение подключения на основе таблицы/struct
- Ручное переключение подключения
- Исходные/репликационные балансировки нагрузки
- Работает для RAW SQL
- Transaction
https://github.com/go-gorm/dbresolver
Использование
import ( |
Automatic connection switching
DBResolver will automatically switch connection based on the working table/struct
For RAW SQL, DBResolver will extract the table name from the SQL to match the resolver, and will use sources
unless the SQL begins with SELECT
(excepts SELECT... FOR UPDATE
), for example:
// `User` Resolver Examples |
Read/Write Splitting
Read/Write splitting with DBResolver based on the current used GORM callbacks.
For Query
, Row
callback, will use replicas
unless Write
mode specified For Raw
callback, statements are considered read-only and will use replicas
if the SQL starts with SELECT
Manual connection switching
// Use Write Mode: read user from sources `db1` |
Transaction
When using transaction, DBResolver will keep using the transaction and won’t switch to sources/replicas based on configuration
But you can specifies which DB to use before starting a transaction, for example:
// Start transaction based on default replicas db |
Балансировка Нагрузки
GORM supports load balancing sources/replicas based on policy, the policy should be a struct implements following interface:
type Policy interface { |
Currently only the RandomPolicy
implemented and it is the default option if no other policy specified.
Пул подключений
db.Use( |