Golang gRPC开发快速入门
下载工具
https://github.com/protocolbuffers/protobuf/releases
对应系统下载即可
- protoc-3.xx.0-win64.zip
- protoc-3.xx.0-linux-x86_64.zip
注意:protoc的版本需要和golang/protobuf保持一致 (尽量自己去下载最新的版本)
下载完成后解压后记得将路径添加到环境变量中
下载go的依赖包
go get github.com/golang/protobuf/protoc-gen-go
proto文件
代码
syntax = "proto3";
option go_package = "/.;proto";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
生成go文件
protoc -I . goods.proto --go_out=plugins=grpc:.
服务端代码
package main
import (
"context"
"demo1/grpc_start/proto"
"google.golang.org/grpc"
"net"
)
type Server struct{}
// 参数必须一致
func (s *Server) SayHello(ctx context.Context, request *proto.HelloRequest) (*proto.HelloReply, error) {
return &proto.HelloReply{
Message: "hello " + request.Name,
}, nil
}
func main() {
// 创建服务
g := grpc.NewServer()
// 注册服务
proto.RegisterGreeterServer(g, &Server{})
listener, err := net.Listen("tcp", "localhost:8080")
if err != nil {
panic("failed Listen:" + err.Error())
}
err = g.Serve(listener)
if err != nil {
panic("failed to start grpc:" + err.Error())
}
}
客户端
package main
import (
"context"
"demo1/grpc_start/proto"
"fmt"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "lzscxb"})
fmt.Println(r.Message)
}