go 和 elixir 的 grpc 通信

步骤

准备

安装 protoc-gen-elixir

mix escript.install hex protobuf

具体步骤

创建项目

mix new appdemo

编写 pb 文件

helloword.proto

syntax = "proto3";

option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

目录结构

├── README.md
├── config
│   └── config.exs
├── helloword.proto
├── lib
│   ├── appdemo.ex
├── mix.exs
└── test
    ├── appdemo_test.exs
    └── test_helper.exs

生成代码

protoc --elixir_out=./lib helloword.proto
protoc -I . --elixir_out=plugins=grpc:./lib/ helloword.proto

lib/server.ex

defmodule Helloworld.Greeter.Server do
  use GRPC.Server, service: Helloworld.Greeter.Service

  @spec say_hello(Helloworld.HelloRequest.t(), GRPC.Server.Stream.t()) ::
          Helloworld.HelloReply.t()
  def say_hello(request, _stream) do
    Helloworld.HelloReply.new(message: "Hello #{request.name}")
  end
end

lib/helloworld_sup.ex

defmodule HelloworldSup do
  use Supervisor

  def start_link(init_arg1, init_arg2) do
    Supervisor.start_link(__MODULE__, [init_arg1, init_arg2], name: __MODULE__)
  end

  @impl true
  def init([_init_arg1, _init_arg2]) do
    children = [
      %{
        id: GRPC.Server.Supervisor,
        start: {GRPC.Server.Supervisor, :start_link, [{Helloworld.Greeter.Server, 50051}]}
      }
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end
end

helloworld_app.ex

defmodule HelloworldApp do
  use Application

  def start(_type, _args) do
    HelloworldSup.start_link("aaa", "bbb")
  end
end

config/config.exs

import Config

# Start server in OTP
config :grpc, start_server: true

mix.exs

def application do
  [
    mod: {HelloworldApp, []},
    extra_applications: [:logger]
  ]
end

# Run "mix help deps" to learn about dependencies.
defp deps do
  [
    {:grpc, "~> 0.5.0"},
    {:protobuf, "~> 0.10"}
  ]
end

启动

mix deps.get
iex -S mix

go的例子

这里

posted @ 2022-10-19 10:48  自由出土文物  阅读(65)  评论(0编辑  收藏  举报