gRPC基础使用方法

使用gRPC(Golang)

1. 安装Protobuf

Prorobut Releases 获取最新的 ProtoBuf 安装包。Linux 可按如下示例步骤操作:

# 下载安装包
$ wget https://github.com/protocolbuffers/protobuf/releases/download/v23.2/protoc-23.2-linux-x86_64.zip

# 解压到 /usr/local 目录下
$ sudo 7z x protoc-23.2-linux-x86_64.zip -o /usr/local

将解压路径下的 bin 目录添加到环境变量:

# 设置环境变量
$ echo "export PATH=$PATH:/usr/local/protobuf/bin" >> /etc/profile

# 刷新环境变量
$ source /etc/profile

检查安装是否成功:

$ protoc --version
libprotoc 23.2

能够正常显示版本,则安装成功。

2. 安装gRPC

使用 go get 命令安装 gRPC:

$ go get google.golang.org/grpc

注意 github.com 域名下的gRPC为旧版本,现在 gRPC 项目已由 google 接管。

安装 go 语言的 protoc 代码生成工具和 grpc 接口生成工具:

# 安装 go 代码生成工具 protoc-gen-go
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest

# 安装 go 语言版本的 grpc 接口生成工具
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

安装完成后在 $GOPATH/bin 路径下,会有这两个工具的执行文件。

3. 新建一个示例项目

目录结构如下:

grpc
    │  go.mod
    │  
    ├─client
    │      main.go
    │
    └─server
        │  main.go
        │
        └─proto
                dog.proto

4. 使用 proto 文件定义服务

编写 proto 文件:

// 指定 proto 的版本
syntax = "proto3";

// 指定生成的 go 文件存放位置及其包名
option go_package = ".;proto";

// 定义服务
service Dog {
    rpc Bark(BarkRequest) returns (BarkResponse);
    rpc Eat(EatRequest) returns (EatResponse);
}

// 定义消息体
message BarkRequest {}

message BarkResponse {
    string responseMsg = 1;
}

message EatRequest {
    string food = 1;
}

message EatResponse {
    string responseMsg = 1;
}

使用编写好的 proto 文件生成 go 语言代码和 gRPC 接口,在 proto 文件所在目录执行以下吗命令:

# 生成 go 语言代码
$ protoc --go_out=. dog.proto

# 生成gRPC 接口
$ protoc --go-grpc_out=. dog.proto

成功执行以上两条命令后,可以看到当前目录中会生成 “dog.pb.go” 和 “dog_grpc.pb.go” 两个 go 文件。
然后将 server 的 proto 文件夹复制一份到 client。

5. 实现服务端

package main

import (
	"context"
	"fmt"
	pb "grpc/server/proto"
	"net"

	"google.golang.org/grpc"
)

// 定义服务类
type server struct {
	pb.UnimplementedDogServer // proto 文件定义的服务接口
}

// 实现在 proto 文件中定义的服务方法
func (s *server) Bark(ctx context.Context, req *pb.BarkRequest) (*pb.BarkResponse, error) {
	return &pb.BarkResponse{ResponseMsg: "汪汪汪...汪"}, nil
}
func (s *server) Eat(ctx context.Context, req *pb.EatRequest) (*pb.EatResponse, error) {
	return &pb.EatResponse{ResponseMsg: "吃" + req.Food}, nil
}

func main() {
	// 开启监听端口
	lis, _ := net.Listen("tcp", ":8801")
	// 创建gRPC服务
	grpcServer := grpc.NewServer()
	// 在grpc服务端注册我们编写的服务
	pb.RegisterDogServer(grpcServer, &server{})

	// 启动服务
	if err := grpcServer.Serve(lis); err != nil {
		fmt.Printf("grpcServer start failed: %v", err)
	}
}

6. 实现客户端

package main

import (
	"context"
	"fmt"
	pb "grpc/client/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

func main() {
	// 连接到服务端,未使用安全连接
	conn, err := grpc.Dial("localhost:8801", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		fmt.Printf("connect to grpcServer failed: %v", err)
		return
	}
	defer conn.Close()

	// 创建 grpc 客户端
	client := pb.NewDogClient(conn)

	// 执行 rpc 调用
	// 调用 Bark 方法
	resp1, _ := client.Bark(context.Background(), &pb.BarkRequest{})
	fmt.Println(resp1.GetResponseMsg())

	// 调用 Eat 方法
	resp2, _ := client.Eat(context.Background(), &pb.EatRequest{Food: "大骨头"})
	fmt.Println(resp2.GetResponseMsg())
}

7. 运行服务

启动服务端程序,然后运行客户端程序。

# 运行客户端,发起 rpc 调用
$ go run main.go 
汪汪汪...汪
吃大骨头

返回值正确,调用成功。

posted @ 2023-06-10 02:32  爱十三的柒  阅读(242)  评论(0)    收藏  举报