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. 运行和测试
-
启动服务端:
go run server/main.go
-
运行客户端:
[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()