在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
概述 rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse) {}
rpc BidiHello(stream HelloRequest) returns (stream HelloResponse){}
brew install protobuf
protoc --version //输出:libprotoc 3.7.1
go get -u github.com/golang/protobuf/proto go get -u github.com/golang/protobuf/protoc-gen-go
go get -u google.golang.org/grpc
syntax = "proto3"; // 指定 proto 版本 package hello; // 指定包名 // 定义 Hello 服务 service Hello { // 定义 SayHello 方法 rpc SayHello(HelloRequest) returns (HelloResponse) {} // 定义 LotsOfReplies 方法 rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse){} } // HelloRequest 请求结构 message HelloRequest { string name = 1; } // HelloResponse 响应结构 message HelloResponse { string message = 1; }
https://developers.google.com/protocol-buffers/
// hello_server.go package hello_controller import ( "fmt" "golang.org/x/net/context" "hello/go_server/proto/hello" ) type HelloController struct{} func (h *HelloController) SayHello(ctx context.Context, in *hello.HelloRequest) (*hello.HelloResponse, error) { return &hello.HelloResponse{Message : fmt.Sprintf("%s", in.Name)}, nil } func (h *HelloController) LotsOfReplies(in *hello.HelloRequest, stream hello.Hello_LotsOfRepliesServer) error { for i := 0; i < 10; i++ { stream.Send(&hello.HelloResponse{Message : fmt.Sprintf("%s %s %d", in.Name, "Reply", i)}) } return nil } // main.go package main import ( "log" "net" "hello/go_server/proto/hello" "hello/go_server/controller/hello_controller" "google.golang.org/grpc" ) const ( Address = "0.0.0.0:9090" ) func main() { listen, err := net.Listen("tcp", Address) if err != nil { log.Fatalf("Failed to listen: %v", err) } s := grpc.NewServer() // 服务注册 hello.RegisterHelloServer(s, &hello_controller.HelloController{}) log.Println("Listen on " + Address) if err := s.Serve(listen); err != nil { log.Fatalf("Failed to serve: %v", err) } }
go run main.go 2019/07/28 17:51:20 Listen on 0.0.0.0:9090
package main
go run main.go 2019/07/28 17:58:13 Hello World 2019/07/28 17:58:13 Hello World Reply 0 2019/07/28 17:58:13 Hello World Reply 1 2019/07/28 17:58:13 Hello World Reply 2 2019/07/28 17:58:13 Hello World Reply 3 2019/07/28 17:58:13 Hello World Reply 4 2019/07/28 17:58:13 Hello World Reply 5 2019/07/28 17:58:13 Hello World Reply 6 2019/07/28 17:58:13 Hello World Reply 7 2019/07/28 17:58:13 Hello World Reply 8
|
请发表评论