golang快速入门--GRPC--基于protobuf构建服务

本文介绍如何使用protobuf构建gRPC服务,并提供跨语言客户端调用示例,包括Go和Python实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本次学习目的

  • 通过protobuf构建grpc服务端,并打包函数给各个语言的客户端

安装

安装protobuf编译器

# 下载地址 https://github.com/protocolbuffers/protobuf/releases
# 加入环境变量
[ ~ ]# protoc --version
libprotoc 3.17.3

安装GO protobuf插件

[ ~ ]# go get -u github.com/golang/protobuf/proto
[ ~ ]# go get -u github.com/golang/protobuf/protoc-gen-go
[ ~ ]# go get -u google.golang.org/grpc

安装Python protobuf

[ ~ ]# pip install protobuf -i https://pypi.tuna.tsinghua.edu.cn/simple/
[ ~ ]# pip install grpcio -i https://pypi.tuna.tsinghua.edu.cn/simple/
[ ~ ]# pip install grpcio-tools -i https://pypi.tuna.tsinghua.edu.cn/simple/

编写.proto文件

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

// 指定包名
package hello;

option go_package = "./proto";

// 指定一个微服务
service Hello {
    // 为服务定义一个方法
    rpc SayHello(HelloReq) returns (HelloRes) {}
    rpc SayI(SayIReq) returns (SayIRes) {}
}
// 以下为请求参数与返回参数
message HelloReq {
    string Name = 1;
}
message HelloRes {
    string Message = 1;
}
message SayIReq {
    string Name = 1;
}
message SayIRes {
    string Message = 1;
}

转化pb文件,并同步给客户端

  • 经过以下操作将会得到文件(这些文件服务端与客户端都将用到)
  • python: hello_pb2.py, hello_pb2_grpc.py
  • go: hello.pb2.go

GO

[ ~ ]# protoc -I . --go_out=plugins=grpc:. ./proto/hello.proto

Python

[ ~ ]# python -m grpc_tools.protoc -I . --python_out=. --grpc_python_out=. ./proto/hello.proto

实现Go服务端

  • 逻辑控制器(controller)
package controller

import "golang.org/x/net/context"
import "grpc-demo/proto"

type HelloController struct {
}

func (c HelloController) SayHello(ctx context.Context, request *proto.HelloReq) (*proto.HelloRes, error) {
	response := proto.HelloRes{}
	response.Message = "你好啊 " + request.Name
	return &response, nil
}

func (c HelloController) SayI(ctx context.Context, request *proto.SayIReq) (*proto.SayIRes, error) {
	response := proto.SayIRes{}
	response.Message = "大家好,我是 " + request.Name
	return &response, nil
}

  • 服务端
package main

import (
	"google.golang.org/grpc"
	"grpc-demo/controller"
	"grpc-demo/proto"
	"log"
	"net"
)

func main() {
	const addr = "0.0.0.0:8000"
	// 监听一个端口
	listen, err := net.Listen("tcp", addr)
	if err != nil {
		log.Panicln(err)
	}
	// 创建一个服务
	server := grpc.NewServer()
	// 注册服务
	proto.RegisterHelloServer(server, &controller.HelloController{})
	log.Println("listen on ", addr)
	// 启动服务
	if err := server.Serve(listen); err != nil {
		log.Panicln(err)
	}

}

实现客户端

GO

package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"grpc-demo/proto"
	"log"
	"time"
)

func main() {
	t1 := time.Now()
	const addr = "0.0.0.0:8000"
	if conn, err := grpc.Dial(addr, grpc.WithInsecure()); err != nil {
		log.Panicln(err)
	} else {
		defer conn.Close()
		client := proto.NewHelloClient(conn)

		ctx := context.Background()

		args := proto.HelloReq{
			Name: "lijiacai",
		}

		result, err := client.SayHello(ctx, &args)
		if err != nil {
			log.Println(err)
		}
		fmt.Println(result)
		fmt.Println(time.Now().Sub(t1).Seconds())
	}

}

Python

import grpc
import proto.hello_pb2 as hello
import proto.hello_pb2_grpc as hello_grpc


def run():
    addr = "localhost:8000"
    conn = grpc.insecure_channel(addr, options=(('grpc.enable_http_proxy', 0),))

    stub = hello_grpc.HelloStub(conn)
    response = stub.SayHello(hello.HelloReq(Name="david"))
    print(response.Message)
    conn.close()


if __name__ == '__main__':
    run()

Grpc接口文档

环境安装

[ ~ ]# go get github.com/fullstorydev/grpcui
[ ~ ]# go get google.golang.org/grpc/credentials/oauth@v1.38.0
[ ~ ]# go get github.com/fullstorydev/grpcui/cmd/grpcui@v1.1.0
[ ~ ]# go install github.com/fullstorydev/grpcui/cmd/grpcui
[ ~ ]# grpcui -plaintext 127.0.0.1:8000

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值