1
votes

I am new to elixir and OTP.

I want to use GenServer.Behaviour for my Server, but for some Reasons elixir can't find it. I have created a mix project, but when I type mix compile I get the following error

== Compilation error on file lib/lecture3.ex == ** (CompileError) lib/lecture3.ex:2: module GenServer.Behaviour is not loaded and could not be found (elixir) expanding macro: Kernel.use/1 lib/lecture3.ex:2: Cache (module)

I guess I have to include the module, but how?

mix.exs:

defmodule LECTURE3.Mixfile do
  use Mix.Project

  def project do
    [app: :lecture3,
     version: "0.1.0",
     elixir: "~> 1.3",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps()]
  end

  def application do
    [applications: [:logger]]
  end

  defp deps do
    []
  end
end

lecture3.ex:

defmodule Cache do
 use GenServer.Behaviour
 def handle_cast({:put, url, page}, {pages, size}) do
    new_pages = Dict.put(pages, url, page)
    new_size = size + byte_size(page)
    {:noreply, {new_pages, new_size}}
 end
 def handle_call({:get, url}, _from, {pages, size}) do
    {:reply, pages[url], {pages, size}}
 end

 def handle_call({:size}, _from, {pages, size}) do
    {:reply, size, {pages, size}}
 end
 def start_link do
    :gen_server.start_link({:local,:cache}, __MODULE__, {HashDict.new, 0}, [])
 end
 def put(url, page) do
    :gen_server.cast(:cache, {:put, url, page})
 end
 def get(url) do
    :gen_server.call(:cache, {:get, url})
 end
 def size do
    :gen_server.call(:cache, {:size})
 end
end

defmodule CacheSupervisor do
 def init(_args) do
    workers = [worker(Cache, [])]
    supervise(workers, strategy: :one_for_one)
 end
 def start_link(domain) do
    :supervisor.start_link(__MODULE__, [domain])
 end
end

Enum.map(["de","edu", "com" ,"it"], fn(x)-> CacheSupervisor.start_link(x)
end)
1

1 Answers

4
votes

Actually GenServer is behavour, so try simply use GenServer. GenServer in Elixir is wrapper for gen_server in Erlang and it provides defaults for undefined functions (so in Erlang you have to always defined 6 functions and in Elixir not).

You don't have to use explicitly gen_server, which is Erlang's module, but use GenServer. Check this out.