通过端点将呼叫发送到GenServer

时间:2017-06-16 18:00:29

标签: asynchronous networking tcp request elixir

如果正在运行GenServer,是否有通过端点向pid发送同步/异步调用的已知方法,而不使用Phoenix框架?

这是一个示例调用(使用python的requests库)将reply项映射到JSON:

iex> give_genserver_endpoint(pid, 'http://mygenserverendpoint/api')
iex> {:ok, 'http://mygenserverendpoint/api'}

>>> requests.get(url='http://mygenserverendpoint/getfood/fruits/colour/red')
>>> '{ "hits" : ["apple", "plum"]}'

1 个答案:

答案 0 :(得分:1)

您可以使用cowboy和plug编写完整的elixir http服务器:

申请模块

defmodule MyApp do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec

    children = [
      worker(MyGenServer, []),
      Plug.Adapters.Cowboy.child_spec(:http, MyRouter, [], [port: 4001])
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

路由器模块

defmodule MyRouter do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/mygenserverendpoint/getfood/fruits/colour/:colour" do
    response_body = MyGenServer.get_fruit_by_colour(colour)
    conn
    |> put_resp_content_type("application/json")
    |> send_resp(conn, 200, Poison.encode(response_body))
  end

  match _ do
    send_resp(conn, 404, "oops")
  end
end

GenServer模块

defmodule MyGenServer do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
  end

  def get_fruit_by_colour(colour) do
    GenServer.call(__MODULE__, {:get_by_colour, colour})
  end

  def handle_call({:get_by_colour, colour}, _from, state) do
    {:reply,  %{"hits" : ["apple", "plum"]}, state}
  end
end