ReadRepos
ReadRepos is an Simple master-slave library for Ecto.
Installation
Add read_repos to your list of dependencies in mix.exs:
def deps do
[{:read_repos, github: "kenta-aktsk/read_repos"}]
endEnsure read_repos is started before your application:
def application do
[applications: [:read_repos]]
endUsage
Add slave database settings to your #{Mix.env}.exs files like below:
# config/dev.exs
config :my_app, MyApp.ReadRepo0,
adapter: Ecto.Adapters.MySQL,
database: "my_app",
hostname: "192.168.0.2",
...
config :my_app, MyApp.ReadRepo1,
adapter: Ecto.Adapters.MySQL,
database: "my_app",
hostname: "192.168.0.3",
...Add supervision tree settings to your application file like below:
# lib/my_app.ex
defmodule MyApp do
use Application
def start(_type, _args) do
children = [
...
]
# add
children = children ++ Enum.map(MyApp.Repo.slaves, &supervisor(&1, []))
...
end
endUse ReadRepos in your Repo module like below:
# lib/my_app/repo.ex
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app
# add
use ReadRepos
end
Then slave databases can be accessed via slave function like below:
MyApp.Entry |> MyApp.Repo.slave.all
MyApp.Entry |> MyApp.Repo.slave.get(1)
# you can get all slave repos like below:
MyApp.Repo.slaves
# => [MyApp.ReadRepo0, MyApp.ReadRepo1]
# also you can access each slave repos directly like below:
MyApp.Entry |> MyApp.ReadRepo0.slave.allSpecify ReadRepo module name
If you want to use ReadRepo module name other than ReadRepo, e.g. Slave, you can specify it by regex like below:
# config/dev.exs
config :my_app, MyApp.Slave0,
...
config :my_app, MyApp.Slave1,
...
# lib/my_app/repo.ex
defmodule MyApp.Repo do
use Ecto.Repo, otp_app: :my_app
# add
use ReadRepos, regexp: ~r/.*MyApp.Slave[0-9]+/
endRemarks
Slave databases are selected randomly.
If there are no slave database settings in config file,
MyApp.Repo.slavereturns master Repo automatically.