How to perform Hot Code Swapping in Elixir- #1

Blackode
Blackode
Dec 28, 2018 · 6 min read

Step 1 — Creating a GenServer

defmodule DemoServer do
use GenServer
@vsn "1"## Client APIdef start_link employee do
GenServer.start_link __MODULE__, employee, []
end

def add_money(pid, value) do
GenServer.call(pid, {:add, value})
end
## Server API
def init(employee) do # initiating state with passed employee details
{:ok, employee}
end

# add the value to the state and returns :ok
def handle_call({:add, value},_from, %{name: name, money: money} = state) do
{:reply, "#{value} added to #{name} ", Map.put(state, :money, money+value)}
end

end

Code Analysis

Load and Ensure DemoServer

$iex demo_server.ex
iex> DemoServer
DemoServer
Loading DemoServer

Ensure it is Working

iex>  employee = %{name: "blackode", money: 30000}
%{money: 30000, name: "blackode"}
iex> {:ok, pid} = DemoServer.start_link employee
{:ok, #PID<0.110.0>}
iex> DemoServer.add_money pid, 30000
"30000 added to blackode "
iex> :sys.get_state pid
%{money: 60000, name: "blackode"}

Step2 — Creating Version 2 for DemoServer

What are the things we are updating in the version 2 ?

$ touch demo_server_2.ex

Code Analysis

Step 3 — Hot Code Swapping

Photo by Suzanne D. Williams on Unsplash

Step 3.1 — Suspending Current Running Process

iex> :sys.suspend pid
:ok
# pid is the process identifier for DemoServer

Step 3.2 — Code Changing from Version 1 to Version 2

iex> c "demo_server_v2.ex"
warning: redefining module DemoServer (current version defined in memory)
demo_server_v2.ex:2
[DemoServer]
iex> :sys.change_code pid, DemoServer, "1", nil
:ok

Step 3.3 — Resuming the Process and Testing

iex> :sys.resume pid
:ok
iex> DemoServer.add_money(pid, 100000)
%{name: "blackode", salary: 160000}
Photo by Samuel Zeller on Unsplash

How to perform Hot Code Swapping using Distillery — #2 — A (Live Demo) GenServer State update

https://t.me/blackoders
if worth_clapping, do: “clap”, else: nil

Happy Coding 🎉

blackode

Coding, thoughts, and ideas.

Blackode

Written by

Blackode

Wrong CODE takes U to the right BUG 🐞 coding, thoughts & ideas

blackode

blackode

Coding, thoughts, and ideas.