欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > go语言gRPC使用流程

go语言gRPC使用流程

2025/4/19 9:10:39 来源:https://blog.csdn.net/yinjinshui/article/details/147227774  浏览:    关键词: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 mainimport ("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、portlistener, 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 mainimport ("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()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词