Last active
March 24, 2019 15:58
-
-
Save L2Eme/c6c51b7936941f22945b94d61a74047a to your computer and use it in GitHub Desktop.
elixir :poolboy example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PoolboyApp.Application do | |
# See https://hexdocs.pm/elixir/Application.html | |
# for more information on OTP Applications | |
@moduledoc false | |
use Application | |
defp poolboy_config do | |
[ | |
{:name, {:local, :worker}}, | |
{:worker_module, PoolboyApp.Worker}, | |
{:size, 5}, | |
{:max_overflow, 2}, | |
# {:strategy, :lifo}, # :lifo :fifo, defualt is :lifo | |
] | |
end | |
def start(_type, _args) do | |
# List all child processes to be supervised | |
children = [ | |
# Starts a worker by calling: PoolboyApp.Worker.start_link(arg) | |
# {PoolboyApp.Worker, arg}, | |
:poolboy.child_spec(:worker, poolboy_config()) | |
] | |
# See https://hexdocs.pm/elixir/Supervisor.html | |
# for other strategies and supported options | |
opts = [strategy: :one_for_one, name: PoolboyApp.Supervisor] | |
Supervisor.start_link(children, opts) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PoolboyApp.Test do | |
@timeout 60000 | |
def start(n) do | |
1..n | |
|> Enum.map(fn i -> async_call_squre_root(i) end) | |
|> Enum.each(fn task -> await_and_inspect(task) end) | |
end | |
defp async_call_squre_root(i) do | |
Task.async(fn -> | |
# transaction(PoolName, Function, timeout \\ :infinite) | |
:poolboy.transaction( | |
:worker, | |
fn pid -> GenServer.call(pid, {:square_root, i}) end, | |
@timeout | |
) | |
end) | |
end | |
defp await_and_inspect(task) do | |
task | |
|> Task.await(@timeout) | |
|> IO.inspect() | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PoolboyApp.Worker do | |
use GenServer | |
def start_link(_) do | |
# GenServer.start_link(module, args, options \\ []) | |
GenServer.start_link(__MODULE__, [], []) | |
end | |
def init(_) do | |
{:ok, nil} | |
end | |
def handle_call({:square_root, x}, _from, state) do | |
IO.puts( | |
"processes #{inspect(self())} calculating square root of #{x}") | |
:timer.sleep(1000) | |
{:reply, :math.sqrt(x), state} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment