一、grpc下载
- protoc下载地址:https://github.com/protocolbuffers/protobuf/releases
- 如果官网下载比较慢以下分享csdn的下载地址
- protoc-21.2-win64.zip:https://download.csdn.net/download/qq23001186/86020796
- protoc-21.2-linux-x86_64.zip:https://download.csdn.net/download/qq23001186/86020770
- go的protoc工具下载:依次执行下列命令(注意go的mod和代理需要设置 ->
GO111MODULE=on
、GOPROXY=https://goproxy.io,direct
)go get -u google.golang.org/protobuf/cmd/protoc-gen-go
go install google.golang.org/protobuf/cmd/protoc-gen-go
go get -u google.golang.org/grpc/cmd/protoc-gen-go-grpc
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc
二、windows下设置
-
protoc环境变量设置
-
在GOPATH的bin目录下找到之前install生成的2个exe文件:拷贝到protoc的bin目录下
-
grpc的proto生成命令:
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative *.proto
- 最新版本的会生成2个文件
- 最新版本的会生成2个文件
-
对应的版本
- protoc-gen-go v1.28.0
- protoc v3.21.2
- protoc-gen-go-grpc v1.2.0
-
helloworld.proto
syntax = "proto3";
option go_package = ".;proto";
// 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;
}
- server:注意Server的结构中需要带上
proto.UnimplementedGreeterServer
否则会报错
package main
import (
"context"
"net"
"google.golang.org/grpc"
"test_project/grpc_test/proto"
)
type Server struct{
proto.UnimplementedGreeterServer
}
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{})
lis, err := net.Listen("tcp", "0.0.0.0:8088")
if err != nil {
return
}
err = g.Serve(lis)
if err != nil {
return
}
}
- client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"test_project/grpc_test/proto"
)
func main() {
//stream
conn, err := grpc.Dial("127.0.0.1:8088", grpc.WithInsecure())
if err != nil {
return
}
defer conn.Close()
c := proto.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "test"})
if err != nil {
return
}
fmt.Println(r.Message)
}