備註:java
a. 安裝 protoc 參考相關文檔,比較簡單 b. 安裝elixir grpc 插件 protoc-gen-elixir 同時配置環境變量
a. 建立項目 mix new appdemo cd appdemo touch 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 b. 生成代碼 protoc --elixir_out=./lib helloword.proto protoc -I . --elixir_out=plugins=grpc:./lib/ helloword.proto 結果以下: ├── README.md ├── config │ └── config.exs ├── helloword.proto ├── lib │ ├── appdemo.ex │ └── helloword.pb.ex ├── mix.exs └── test ├── appdemo_test.exs └── test_helper.exs 內容: defmodule Helloworld.HelloRequest do use Protobuf @type t :: %__MODULE__{ name: String.t() } defstruct [:name] field :name, 1, optional: true, type: :string end defmodule Helloworld.HelloReply do use Protobuf @type t :: %__MODULE__{ message: String.t() } defstruct [:message] field :message, 1, optional: true, type: :string end defmodule Helloworld.Greeter.Service do use GRPC.Service, name: "helloworld.Greeter" rpc :SayHello, Helloworld.HelloRequest, Helloworld.HelloReply end defmodule Helloworld.Greeter.Stub do use GRPC.Stub, service: Helloworld.Greeter.Service end
a. server端實現代碼 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 b. 項目使用opt 進行運行,具體來講是supervisor lib/helloworld_app.ex defmodule HelloworldApp do use Application def start(_type, _args) do import Supervisor.Spec children = [ supervisor(GRPC.Server.Supervisor, [{Helloworld.Greeter.Server, 50051}]) ] opts = [strategy: :one_for_one, name: HelloworldApp] Supervisor.start_link(children, opts) end end c. mix.exs 啓動配置 def application do [mod: {HelloworldApp, []}, applications: [:logger, :grpc]] end defp deps do [ {:grpc, github: "tony612/grpc-elixir"}, {:dialyxir, "~> 0.5", only: [:dev, :test], runtime: false}, ] end d. config/config.exs use Mix.Config # Start server in OTP config :grpc, start_server: true
mix deps.get,compile iex -S mix
參考 https://github.com/rongfengliang/grpc-elixir
https://github.com/rongfengliang/grpc-elixir https://github.com/rongfengliang/gprc-elixir-server https://github.com/tony612/grpc-elixir