当前位置: 首页 > news >正文

go语言gRPC使用流程

1. 安装工具和依赖

  • 安装 Protocol Buffers 编译器 (protoc)
    下载地址:https://github.com/protocolbuffers/protobuf/releases
    使用说明:https://protobuf.dev/
	【centos环境】yum方式安装:protoc
	[root@localhost demo-first]#  yum install protobuf-compiler -y
  • 安装 Go 插件

    go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
    

2. 定义服务接口(.proto 文件)

创建 greeter.proto 文件:

syntax = "proto3";

option go_package = "./greeterService";

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

message HelloRequest {
  string name = 1 ;
}

message HelloResponse {
  string message = 1;
}

3. 生成代码

使用 protoc 生成 Go 代码:

[root@localhost demo-first]# go mod init demo-first
go: creating new go.mod: module demo-first

[root@localhost demo-first]# go get -u github.com/golang/protobuf/protoc-gen-go
go: downloading github.com/golang/protobuf v1.5.4
go: module github.com/golang/protobuf is deprecated: Use the "google.golang.org/protobuf" module instead.
go: added github.com/golang/protobuf v1.5.4
go: added google.golang.org/protobuf v1.36.6
[root@localhost demo-first]# go get -u google.golang.org/grpc
[root@localhost demo-first]# export PATH=$PATH:$GOPATH/bin

[root@localhost demo-first]# protoc --go_out=. --go-grpc_out=. greeter.proto
[root@localhost demo-first]# ls
go.mod  go.sum  greeter.proto  greeterService  server  shuoming.md
[root@localhost demo-first]# ls greeterService/
greeter_grpc.pb.go  greeter.pb.go


生成的文件:greeter.pb.go(数据序列化)和 greeter_grpc.pb.go(gRPC 服务)。


4. 实现服务端

创建 server/main.go

package main

import (
	"context"
	"demo-first/greeterService"
	"fmt"
	"net"

	"google.golang.org/grpc"
)

// rpc远程调用的接口,需要实现greeter.proto中定义的Greeter服务接口,以及里面的方法
// 1.定义远程调用的结构体和方法,这个结构体需要实现greeterServer的接口
type Greeter struct {
	greeterService.UnimplementedGreeterServer
}

func (this Greeter) SayHello(c context.Context, req *greeterService.HelloRequest) (*greeterService.HelloResponse, error) {
	fmt.Println(c, req)
	return &greeterService.HelloResponse{
		Message: "增加成功" + req.Name,
	}, nil
}

func main() {
	//初始化一个grpc服务
	grpcServer := grpc.NewServer()
	fmt.Println("grpcServer", grpcServer)
	//注册服务
	greeterService.RegisterGreeterServer(grpcServer, new(Greeter))

	//3. 设置监听, 指定 IP、port
	listener, err := net.Listen("tcp", "0.0.0.0:8068")
	if err != nil {
		fmt.Println(err)
	}

	// 4退出关闭监听
	defer listener.Close()

	// 5.启动服务
	if err := grpcServer.Serve(listener); err != nil {
		fmt.Println(err)
	}
	fmt.Println("服务启动成功:8068")
}


5. 编写客户端

创建 client/main.go

package main

import (
	"context"
	"demo-first/greeterService"
	"fmt"

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

func main() {
	// 1、连接服务器
	/*
	   credentials.NewClientTLSFromFile :从输入的证书文件中为客户端构造TLS凭证。
	   grpc.WithTransportCredentials :配置连接级别的安全凭证(例如,TLS/SSL),返回一个
	   DialOption,用于连接服务器。
	*/
	grpcClient, err := grpc.Dial("127.0.0.1:8068", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		fmt.Println(err)
	}

	// 2、调用远程服务
	client := greeterService.NewGreeterClient(grpcClient)

	// 3、调用服务方法
	resp, err := client.SayHello(context.Background(), &greeterService.HelloRequest{
		Name: "张三",
	})
	if err != nil { // 调用失败
		fmt.Println(err)
	} else { // 调用成功
		fmt.Println(resp.Message) // 输出服务端返回的消息
	}

	// 4、关闭连接
	grpcClient.Close()
}


 如果库存有缺失自行执行go get 获取
[root@localhost demo-first]# go mod vendor
[root@localhost demo-first]# ls
client  go.mod  go.sum  greeter.proto  greeterService  server  shuoming.md  vendor

6. 运行和测试

  1. 启动服务端

    go run server/main.go
    
  2. 运行客户端

    [root@localhost demo-first]# go run client/main.go 
    增加成功张三
    
    

关键概念

  • 通信模式
    • Unary RPC:一对一(普通 RPC)。
    • Server Streaming:服务端流式响应。
    • Client Streaming:客户端流式请求。
    • Bidirectional Streaming:双向流式通信。
  • 安全性
    • 使用 grpc.WithTransportCredentials(credentials.NewTLS(...)) 启用 TLS。
  • 元数据(Metadata):传递头部信息(如认证 Token)。

常见问题排查

  • Proto 路径错误:确保生成的代码导入路径正确。
  • 端口冲突:检查服务端监听的端口是否被占用。
  • TLS 配置:生产环境务必启用 TLS,测试可用 grpc.WithInsecure()

相关文章:

  • AI数据分析的优势分析
  • 浙江大学DeepSeek系列专题线上公开课第二季第五期即将上线!deepseek人文艺术之美专场来啦!
  • 什么是COSMIC功能点评估方法
  • [福游宝——AI智能旅游信息查询平台]全栈AI项目-阶段二:聊天咨询业务组件开发
  • 系统性能优化总结与思考-第一部分
  • 简简单单实现一个Python+Selenium的自动化测试框架
  • LabVIEW 发电机励磁系统监测与诊断
  • CExercise_05_1伪随机数_1写一个随机发牌程序,由用户指定发几张票,然后打印用户得到的手牌。
  • 前端常考面试题目详解
  • 软件更新 | 以太网通信仿真功能已上线!TSMaster 202503 版本更新速览
  • C++中的高阶函数
  • Redis之缓存穿透
  • 【NLP】24. spaCy 教程:自然语言处理核心操作指南(进阶)
  • 《AI大模型应知应会100篇》第5篇:大模型发展简史:从BERT到ChatGPT的演进
  • InnoDB的MVCC实现原理?MVCC如何实现不同事务隔离级别?MVCC优缺点?
  • 基于LangGraph的智能报告生成平台项目分析
  • 树莓派超全系列教程文档--(23)内核参数
  • kubectl命令补全以及oc命令补全
  • ArmSoM Sige5 CM5:RK3576 上 Ultralytics YOLOv11 边缘计算新标杆
  • 【KWDB创作者计划】容器赋能KaiwuDB:探索浪潮数据库KWDB2.2.0 实战指南
  • 收藏家尤伦斯辞世,曾是中国当代艺术的推手与收藏者
  • 两日内连续施压,特朗普再次喊话美联储降息
  • 平安银行一季度净赚超140亿元降5.6%,营收降13.1%
  • 夜读丨“看看世界”本身就是一种意义
  • 财政部:一季度证券交易印花税411亿元,同比增长60.6%
  • 浙江金华一副镇长被指殴打村民,镇党委称仍在调查核实