elixir grpc 试用
备注:
elixir grpc 封装测试
1. 安装
a. 安装 protoc 参考相关文档,比较简单
b. 安装elixir grpc 插件 protoc-gen-elixir 同时配置环境变量
2. 基本项目使用
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
3. 项目使用(接上面项目)
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
4. 启动
mix deps.get,compile
iex -S mix
5. golang client demo
参考 https://github.com/rongfengliang/grpc-elixir
6. 参考资料
https://github.com/rongfengliang/grpc-elixir
https://github.com/rongfengliang/gprc-elixir-server
https://github.com/tony612/grpc-elixir