Created
March 18, 2018 06:36
-
-
Save abhin4v/8f8fb9ca4c561b946172fc1880f4cb62 to your computer and use it in GitHub Desktop.
Simple cache using GenServer in Elixir
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 CacheServer do | |
use GenServer | |
@name CS | |
## Client API | |
def start_link(opts \\ []) do | |
GenServer.start_link(__MODULE__, :ok, opts ++ [name: CS]) | |
end | |
def write(key, val) do | |
GenServer.cast(@name, {:write, key, val}) | |
end | |
def read(key) do | |
GenServer.call(@name, {:read, key}) | |
end | |
def delete(key) do | |
GenServer.cast(@name, {:delete, key}) | |
end | |
def clear() do | |
GenServer.cast(@name, {:clear}) | |
end | |
def exists?(key) do | |
GenServer.call(@name, {:exists?, key}) | |
end | |
## Server API | |
def init(:ok) do | |
{:ok, %{}} | |
end | |
def handle_call({:read, key}, _from, cache) do | |
{:reply, Map.fetch(cache, key), cache} | |
end | |
def handle_call({:exists?, key}, _from, cache) do | |
{:reply, Map.has_key?(cache, key), cache} | |
end | |
def handle_cast({:write, key, val}, cache) do | |
{:noreply, Map.put(cache, key, val)} | |
end | |
def handle_cast({:delete, key}, cache) do | |
{:noreply, Map.delete(cache, key)} | |
end | |
def handle_cast({:clear}, _cache) do | |
{:noreply, %{}} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment