【笔记】GRPC快速入门

前言

GRPC快速入门

下载依赖

1
2
3
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go get google.golang.org/grpc

编写Proto代码

helloword/;golang:配置Proto代码存放位置和编译后的语言

helloword/helloword.proto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
syntax = "proto3";

option go_package="helloword/;helloword";

package hello_grpc;

message Req {
string message = 1;
}

message Res {
string message = 1;
}

service HelloGRPC {
rpc SayHi(Req) returns (Res);
}

编译Proto代码

helloword/helloword.proto:Proto代码的存放路径

1
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative helloword/helloword.proto
  • 编译完成后会在Proto代码的同级目录下生成helloword.pb.gohelloword_grpc.pb.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
package main

import (
"context"
"fmt"
"google.golang.org/grpc"
"grpcdemo/helloword"
"net"
)

type Server struct {
helloword.UnimplementedHelloGRPCServer
}

func (server *Server) SayHi(context context.Context, request *helloword.Req) (response *helloword.Res, err error) {
fmt.Println(request.GetMessage())
return &helloword.Res{Message: "pong"}, nil
}

func main() {
listen, _ := net.Listen("tcp", "0.0.0.0:8080")
server := grpc.NewServer()
helloword.RegisterHelloGRPCServer(server, new(Server))
server.Serve(listen)
}

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
"context"
"fmt"
"google.golang.org/grpc"
"grpcdemo/helloword"
)

func main() {
connect, _ := grpc.Dial("127.0.0.1:8080", grpc.WithInsecure())
defer connect.Close()
client := helloword.NewHelloGRPCClient(connect)
response, _ := client.SayHi(context.Background(), &helloword.Req{Message: "ping"})
fmt.Println(response.GetMessage())
}

完成

参考文献

哔哩哔哩——go圈里最会写js的奇淼