参考文章
Quick start | Go | gRPC
Quick start | Go | gRPC
环境搭建
安装protoc 转换工具,该工具无论是server 或者是clinet 都是可以准备一个
https://github.com/protocolbuffers/protobuf/releases
然后创建一个新的项目
拉一下
1 2 3
| go get github.com/golang/protobuf/proto go get google.golang.org/grpc go install github.com/golang/protobuf/protoc-gen-go
|
然后需要配置环境,这里介绍一个 linux 配置环境变量的方法
然后添加对应的路径在后面
如
因为我云服务器我懒得配置成所有用户的了
然后使用
测试环境是否搭建成功
首先编写一个protobuf 文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| syntax = "proto3"; package hello_grpc;
option go_package = "/hello_grpc";
service HelloService { rpc SayHello (HelloRequest) returns (HelloResponse) {} }
message HelloRequest { string name = 1; string message = 2; }
message HelloResponse{ string name = 1; string message = 2; }
|
我的目录树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| D:. │ go.mod │ go.sum │ ├─.idea │ .gitignore │ deployment.xml │ GRPCStudyServer.iml │ modules.xml │ webServers.xml │ workspace.xml │ ├─cmd │ main.go │ server.exe │ ├─grpcProto │ │ hello.proto │ │ │ └─hello_grpc │ hello.pb.go │ ├─grpcServer │ helloGrpc.go │ └─script set.bat set.sh
|
然后再set.bat 或者set.sh 里面填写
1
| protoc -I ../grpc_proto --go_out=plugins=grpc:../grpcProto ../grpcProto/hello.proto
|
1
| protoc -I ../grpcProto --go_out=plugins=grpc:../grpcProto ../grpcProto/hello.proto
|
然后执行就行了
命令里的重点
1
| protoc -I ../grpcProto --go_out=plugins=grpc:文件生成的目录 proto文件路径
|
然后就生成了hello_grpc 文件夹
能生成说明环境配置成功
server 搭建
当文件创建之后,就必须实现他的方法
helloGrpc.go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package grpcServer
import ( "GRPCStudyServer/grpcProto/hello_grpc" "context" "fmt" )
type HelloGrpcServer struct { }
func (s *HelloGrpcServer) SayHello(ctx context.Context, request *hello_grpc.HelloRequest) (response *hello_grpc.HelloResponse, err error) { fmt.Println("request:", request) response = &hello_grpc.HelloResponse{ Message: "AU9U5T", } return response, nil }
|
这样就相当于实现了他的方法,然后我们再注册一个服务就行了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| func main() { listen, err := net.Listen("tcp", ":8080") if err != nil { panic(err) } defer listen.Close() s := grpc.NewServer()
server := se.HelloGrpcServer{}
hello_grpc.RegisterHelloServiceServer(s, &server) fmt.Println("grpc server start") g.
}
|
client 搭建
建议这个观看
快速入门 |前往 |gRPC的
还是一样的,首先拷贝同样的文件,到项目目录
然后生成对应的go 文件
然后再进行连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package main
import ( "GRPCStudy/grpc_proto/hello_grpc" "context" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "time" )
func main() { addr := "139.159.140.145:8080" conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { panic(err) } defer conn.Close()
client := hello_grpc.NewHelloServiceClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() req, err := client.SayHello(ctx, &hello_grpc.HelloRequest{ Name: "gRPC", }) if err != nil { panic(err) } println(req.Message)
}
|