自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python和Go實(shí)現(xiàn)簡(jiǎn)單Grpc服務(wù)

開(kāi)發(fā) 前端
在 Grpc 中,使用 Protocol Buffers(簡(jiǎn)稱 Protobuf)來(lái)定義服務(wù)和消息的結(jié)構(gòu)。Protobuf 是一種輕量級(jí)的數(shù)據(jù)交換格式,它可以定義結(jié)構(gòu)化數(shù)據(jù)的模式,并生成相應(yīng)的代碼用于序列化和反序列化。

一、簡(jiǎn)介

Grpc 使用了 Google 的 Protocol Buffers 作為接口定義語(yǔ)言(IDL),并使用 HTTP/2 作為傳輸協(xié)議。它支持多種編程語(yǔ)言,包括 C++、Java、Python、Go、Node.js 等。Grpc 提供了強(qiáng)大的功能,如雙向流、流式處理、身份驗(yàn)證和攔截器等。

Grpc 的核心概念是服務(wù)和消息。服務(wù)定義了一組方法,客戶端可以通過(guò)這些方法與服務(wù)端進(jìn)行交互。消息定義了數(shù)據(jù)的結(jié)構(gòu),用于在服務(wù)和客戶端之間傳遞。

二、安裝proto

下載proto文件:

安裝后設(shè)置系統(tǒng)環(huán)境變量,然后打開(kāi)控制臺(tái),執(zhí)行protoc -h命令驗(yàn)證是否安裝成功。

三、初始化工程

Python中使用Grpc

初始化工程

mkdir grpc_demo
cd grpc_demo
pdm init

安裝Python工具庫(kù)

pdm add grpcio
pdm add grpcio-tools

Go中使用Grpc

初始化工程

mkdir grpc_demo
cd grpc_demo
go mod init grpc_demo

安裝Go工具庫(kù)

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

四、定義服務(wù)和消息

在 Grpc 中,使用 Protocol Buffers(簡(jiǎn)稱 Protobuf)來(lái)定義服務(wù)和消息的結(jié)構(gòu)。Protobuf 是一種輕量級(jí)的數(shù)據(jù)交換格式,它可以定義結(jié)構(gòu)化數(shù)據(jù)的模式,并生成相應(yīng)的代碼用于序列化和反序列化。

定義服務(wù)和消息的步驟如下:

  1. 創(chuàng)建proto文件夾:proto,將對(duì)應(yīng)的proto文件創(chuàng)建在里面
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 文件編譯成所需語(yǔ)言的代碼。
  • 在Python中運(yùn)行以下命令:
pdm run python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I . hello.proto
- —python_out:生成的Python文件存儲(chǔ)目錄。
- —grpc_python_out:生成的Grpc使用的Python文件存儲(chǔ)目錄。
- -I:proto文件的目錄,這里的目錄地址將影響proto文件相互引用的路徑。

執(zhí)行完以上命令后,會(huì)在指定目錄下生成:`hello_pb2.py`和`hello_pb2_grpc.py` 兩個(gè)文件。
  • 在Go中運(yùn)行以下命令:
protoc --go_out=. --go-grpc_out=. -I . hello.proto
- —go_out:生成的Go文件存儲(chǔ)目錄。
- —go-grpc_out:生成的Grpc使用的Go文件存儲(chǔ)目錄。
- -I:proto文件的目錄。

執(zhí)行完以上命令后,會(huì)在指定目錄下生成:`hello_pb.g`o和`hello_grpc.pb.go` 兩個(gè)文件。

五、編寫(xiě)服務(wù)端

在 Grpc 中,編寫(xiě)服務(wù)端需要執(zhí)行以下幾個(gè)步驟:

  1. 導(dǎo)入所需的庫(kù)和生成的消息定義文件:

Go實(shí)現(xiàn):

package main

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

Python實(shí)現(xiàn):

import grpc
from concurrent import futures
from proto import hello_pb2_grpc, hello_pb2
  1. 創(chuàng)建一個(gè)類(lèi)繼承自自動(dòng)生成的服務(wù)定義類(lèi),并實(shí)現(xiàn)其中定義的方法:

Go實(shí)現(xiàn):

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實(shí)現(xiàn):

class GreeterServicer(hello_pb2_grpc.GreeterServicer):
    def SayHello(self, request, context):
        return hello_pb2.HelloReply(message='Hello, %s!' % request.name)
  1. 創(chuàng)建一個(gè) gRPC 服務(wù)器并將服務(wù)實(shí)現(xiàn)添加到服務(wù)器中:

Go實(shí)現(xiàn):

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實(shí)現(xiàn):

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. 啟動(dòng)服務(wù)器:

Go實(shí)現(xiàn):

func main() {
    serve()
}

Python實(shí)現(xiàn):

if __name__ == '__main__':
    serve()

以上代碼實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Grpc服務(wù)端,其中SayHello是在服務(wù)定義中聲明的方法,我們可以根據(jù)需求添加更多的方法和邏輯。

六、編寫(xiě)客戶端

編寫(xiě) Grpc 客戶端的步驟如下:

  1. 導(dǎo)入所需的庫(kù)和生成的消息定義文件:

Go實(shí)現(xiàn):

package main

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

Python實(shí)現(xiàn):

import grpc
from proto import hello_pb2_grpc, hello_pb2
  1. 創(chuàng)建一個(gè)Grpc通道:

Go實(shí)現(xiàn):

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實(shí)現(xiàn):

channel = grpc.insecure_channel('localhost:50051')
  1. 創(chuàng)建一個(gè) Stub 對(duì)象,用于調(diào)用服務(wù)端的方法:

Go實(shí)現(xiàn):

stub := proto.NewGreeterClient(conn)

Python實(shí)現(xiàn):

stub = hello_pb2_grpc.GreeterStub(channel)
  1. 調(diào)用服務(wù)端的方法:

Go實(shí)現(xiàn):

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實(shí)現(xiàn):

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

以上分別用Python和Go實(shí)現(xiàn)了簡(jiǎn)單的Grpc服務(wù)端和客戶端。

責(zé)任編輯:武曉燕 來(lái)源: 今日頭條
相關(guān)推薦

2025-02-04 13:53:18

NixGogRPC

2022-10-17 00:14:55

微服務(wù)稅mock代理服務(wù)

2022-06-07 08:19:30

gRPCBallerina微服務(wù)

2024-01-02 12:17:44

Go傳統(tǒng)遠(yuǎn)程

2022-01-26 00:03:00

高可用gRPC微服務(wù)

2021-11-24 16:51:03

gRPCGoPython

2022-03-22 09:22:21

Go kitgRPC網(wǎng)絡(luò)傳輸

2022-10-26 07:26:38

2022-05-06 09:22:25

Go泛型

2023-11-25 09:31:20

Go事件管理器

2023-11-25 09:41:34

GogRPCHandler

2023-03-05 23:11:07

Go語(yǔ)言服務(wù)

2023-09-06 07:17:57

2021-06-10 07:49:26

RPCgRPC模式

2022-02-20 23:15:46

gRPCGolang語(yǔ)言

2023-07-04 07:45:11

gogRPC服務(wù)

2011-08-05 13:41:46

Go

2023-01-11 15:17:01

gRPC.NET 7

2022-03-29 10:36:32

技術(shù)架構(gòu)微服務(wù)

2021-08-03 15:33:05

gRPC服務(wù)器
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)