简体   繁体   English

通过端点将呼叫发送到GenServer

[英]send calls via an endpoint to a GenServer

Given a running GenServer , is there a known way to send synchronous/asynchronous calls to the pid via an endpoint, without using the Phoenix framework? 给定一个正在运行的GenServer ,是否有一种已知的方法可以通过端点在不使用Phoenix框架的情况下向pid发送同步/异步调用?

Here's an example call (using python's requests library) that maps the reply term to JSON: 这是一个示例调用(使用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"]}'

You can write a complete elixir http server using cowboy and plug: 您可以使用牛仔和插件编写完整的elixir http服务器:

Application Module 应用模块

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

Router Module 路由器模块

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 module 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM