Python和Go实现简单Grpc服务

开发 前端
在 Grpc 中,使用 Protocol Buffers(简称 Protobuf)来定义服务和消息的结构。Protobuf 是一种轻量级的数据交换格式,它可以定义结构化数据的模式,并生成相应的代码用于序列化和反序列化。

一、简介

Grpc 使用了 Google 的 Protocol Buffers 作为接口定义语言(IDL),并使用 HTTP/2 作为传输协议。它支持多种编程语言,包括 C++、Java、Python、Go、Node.js 等。Grpc 提供了强大的功能,如双向流、流式处理、身份验证和拦截器等。

Grpc 的核心概念是服务和消息。服务定义了一组方法,客户端可以通过这些方法与服务端进行交互。消息定义了数据的结构,用于在服务和客户端之间传递。

二、安装proto

下载proto文件:

安装后设置系统环境变量,然后打开控制台,执行protoc -h命令验证是否安装成功。

三、初始化工程

Python中使用Grpc

初始化工程

mkdir grpc_demo
cd grpc_demo
pdm init

安装Python工具库

pdm add grpcio
pdm add grpcio-tools

Go中使用Grpc

初始化工程

mkdir grpc_demo
cd grpc_demo
go mod init grpc_demo

安装Go工具库

go install github.com/golang/protobuf/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

四、定义服务和消息

在 Grpc 中,使用 Protocol Buffers(简称 Protobuf)来定义服务和消息的结构。Protobuf 是一种轻量级的数据交换格式,它可以定义结构化数据的模式,并生成相应的代码用于序列化和反序列化。

定义服务和消息的步骤如下:

  1. 创建proto文件夹:proto,将对应的proto文件创建在里面
syntax = "proto3";

option go_package = ".;proto";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
  1. 使用 Protobuf 编译器将 .proto 文件编译成所需语言的代码。
  • 在Python中运行以下命令:
pdm run python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I . hello.proto
- —python_out:生成的Python文件存储目录。
- —grpc_python_out:生成的Grpc使用的Python文件存储目录。
- -I:proto文件的目录,这里的目录地址将影响proto文件相互引用的路径。

执行完以上命令后,会在指定目录下生成:`hello_pb2.py`和`hello_pb2_grpc.py` 两个文件。
  • 在Go中运行以下命令:
protoc --go_out=. --go-grpc_out=. -I . hello.proto
- —go_out:生成的Go文件存储目录。
- —go-grpc_out:生成的Grpc使用的Go文件存储目录。
- -I:proto文件的目录。

执行完以上命令后,会在指定目录下生成:`hello_pb.g`o和`hello_grpc.pb.go` 两个文件。

五、编写服务端

在 Grpc 中,编写服务端需要执行以下几个步骤:

  1. 导入所需的库和生成的消息定义文件:

Go实现:

package main

import (
  "context"
  "go_demo/proto"
  "google.golang.org/grpc"
  "net"
)

Python实现:

import grpc
from concurrent import futures
from proto import hello_pb2_grpc, hello_pb2
  1. 创建一个类继承自自动生成的服务定义类,并实现其中定义的方法:

Go实现:

type Server struct {
  proto.UnimplementedGreeterServer
}

func (s *Server) SayHello(ctx context.Context, in *proto.HelloRequest) (*proto.HelloReply, error) {
  return &proto.HelloReply{Message: "Hello Go " + in.Name}, nil
}

Python实现:

class GreeterServicer(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
  1. 创建一个 gRPC 服务器并将服务实现添加到服务器中:

Go实现:

func serve() {
    g := grpc.NewServer()
    proto.RegisterGreeterServer(g, &Server{})
    lis, err := net.Listen("tcp", ":50051")
    if err != nil {
      panic("failed to listen: " + err.Error())
    }
    err = g.Serve(lis)
    if err != nil {
      panic("failed to start serve: " + err.Error())
    }
}

Python实现:

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    server.add_insecure_port('0.0.0.0:50051')
    server.start()
    server.wait_for_termination()
  1. 启动服务器:

Go实现:

func main() {
    serve()
}

Python实现:

if __name__ == '__main__':
    serve()

以上代码实现一个简单的Grpc服务端,其中SayHello是在服务定义中声明的方法,我们可以根据需求添加更多的方法和逻辑。

六、编写客户端

编写 Grpc 客户端的步骤如下:

  1. 导入所需的库和生成的消息定义文件:

Go实现:

package main

import (
  "context"
  "fmt"
  "go_demo/proto"
  "google.golang.org/grpc"
  "google.golang.org/grpc/credentials/insecure"
)

Python实现:

import grpc
from proto import hello_pb2_grpc, hello_pb2
  1. 创建一个Grpc通道:

Go实现:

conn, err := grpc.Dial("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
  panic("failed to dial: " + err.Error())
}
defer conn.Close()

Python实现:

channel = grpc.insecure_channel('localhost:50051')
  1. 创建一个 Stub 对象,用于调用服务端的方法:

Go实现:

stub := proto.NewGreeterClient(conn)

Python实现:

stub = hello_pb2_grpc.GreeterStub(channel)
  1. 调用服务端的方法:

Go实现:

response, err := stub.SayHello(context.Background(), &proto.HelloRequest{Name: "world"})
if err != nil {
  panic("failed to say hello: " + err.Error())
}
fmt.Println(response.Message)

Python实现:

response = stub.SayHello(hello_pb2.HelloRequest(name='tom'))
print(response.message)

以上分别用Python和Go实现了简单的Grpc服务端和客户端。

责任编辑:武晓燕 来源: 今日头条
相关推荐

2022-10-17 00:14:55

微服务税mock代理服务

2022-06-07 08:19:30

gRPCBallerina微服务

2024-01-02 12:17:44

Go传统远程

2022-01-26 00:03:00

高可用gRPC微服务

2021-11-24 16:51:03

gRPCGoPython

2022-03-22 09:22:21

Go kitgRPC网络传输

2023-11-25 09:41:34

GogRPCHandler

2022-10-26 07:26:38

2022-05-06 09:22:25

Go泛型

2023-03-05 23:11:07

Go语言服务

2023-09-06 07:17:57

2023-11-25 09:31:20

Go事件管理器

2022-02-20 23:15:46

gRPCGolang语言

2021-06-10 07:49:26

RPCgRPC模式

2023-07-04 07:45:11

gogRPC服务

2011-08-05 13:41:46

Go

2021-08-03 15:33:05

gRPC服务器

2023-01-11 15:17:01

gRPC.NET 7

2022-03-29 10:36:32

技术架构微服务

2023-03-03 08:19:35

KubernetesgRPC
点赞
收藏

51CTO技术栈公众号