# grpc-demo
**Repository Path**: Ultron2018/grpc-demo
## Basic Information
- **Project Name**: grpc-demo
- **Description**: 一个完整的 Go gRPC 示例,包含普通 RPC 和流式 RPC 两种通信模式。
- **Primary Language**: Unknown
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2026-01-22
- **Last Updated**: 2026-01-22
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# gRPC Go 示例项目
一个完整的 Go gRPC 示例,包含普通 RPC 和流式 RPC 两种通信模式。
## 📋 项目结构
```
grpc-demo/
├── go.mod # Go 模块定义
├── hello.proto # Protocol Buffers 定义文件
├── helloworld/ # 生成的 gRPC 代码
│ ├── hello.pb.go # Protocol Buffers 消息结构
│ └── hello_grpc.pb.go # gRPC 客户端和服务端接口
├── server/ # 服务端实现
│ └── main.go # 服务端主程序
└── client/ # 客户端实现
└── main.go # 客户端主程序
```
## 🚀 快速开始
### 1. 前置要求
- **Go 1.21+** ([下载地址](https://golang.org/dl/))
- **protoc 编译器** ([下载地址](https://github.com/protocolbuffers/protobuf/releases))
### 2. 安装依赖
```bash
# 安装 Go 插件
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
```
### 3. 生成 gRPC 代码
```bash
# 从 .proto 文件生成 Go 代码
protoc --go_out=. --go-grpc_out=. hello.proto
```
这会生成 `helloworld/` 目录,包含:
- `hello.pb.go` - Protocol Buffers 消息结构
- `hello_grpc.pb.go` - gRPC 客户端和服务端接口
### 4. 更新模块路径
修改 `go.mod` 文件中的模块路径为你自己的模块路径:
```go
module your-module-path
go 1.21
require (
google.golang.org/grpc v1.60.0
google.golang.org/protobuf v1.31.0
)
```
### 5. 下载依赖
```bash
go mod tidy
```
## 📡 运行示例
### 启动服务端
```bash
# 终端 1:启动 gRPC 服务器
go run server/main.go
# 输出示例:
# 2024/01/19 10:30:00 server listening at [::]:50051
```
### 启动客户端
```bash
# 终端 2:运行客户端
go run client/main.go
# 输出示例:
# 2024/01/19 10:30:05 Greeting: Hello World
# 2024/01/19 10:30:05 Stream reply: Hello Streaming World - message 1
# 2024/01/19 10:30:06 Stream reply: Hello Streaming World - message 2
# 2024/01/19 10:30:07 Stream reply: Hello Streaming World - message 3
# 2024/01/19 10:30:08 Stream reply: Hello Streaming World - message 4
# 2024/01/19 10:30:09 Stream reply: Hello Streaming World - message 5
```
## 📊 示例说明
### 1. 服务定义 (hello.proto)
```protobuf
syntax = "proto3";
package helloworld;
option go_package = "./helloworld";
service Greeter {
// 普通 RPC 调用
rpc SayHello (HelloRequest) returns (HelloReply) {}
// 服务器流式 RPC
rpc SayHelloStream (HelloRequest) returns (stream HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
```
### 2. 服务端功能
**server/main.go** 实现了两个 RPC 方法:
1. **普通 RPC (`SayHello`)**
- 接收单个请求,返回单个响应
- 立即返回结果
2. **流式 RPC (`SayHelloStream`)**
- 接收单个请求,返回流式响应
- 每秒发送一条消息,共发送 5 条
- 演示服务器端流式传输
### 3. 客户端功能
**client/main.go** 展示了两种调用方式:
1. **同步调用** - 请求/响应模式
2. **流式调用** - 接收服务器推送的多个响应
## 🔧 API 端点
| 方法 | 类型 | 描述 |
|------|------|------|
| `/helloworld.Greeter/SayHello` | 普通 RPC | 单次请求/响应 |
| `/helloworld.Greeter/SayHelloStream` | 服务器流式 RPC | 单次请求,流式响应 |
## 🛠️ 开发工具
### 使用 grpcurl 测试
```bash
# 安装 grpcurl
go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest
# 列出所有服务
grpcurl -plaintext localhost:50051 list
# 列出 Greeter 服务的方法
grpcurl -plaintext localhost:50051 list helloworld.Greeter
# 调用 SayHello 方法
grpcurl -plaintext -d '{"name": "Alice"}' \
localhost:50051 helloworld.Greeter/SayHello
```
### 使用 Evans 交互式客户端
```bash
# 安装 Evans
go install github.com/ktr0731/evans@latest
# 连接到服务
evans -p 50051 repl
# 在 Evans 中:
show service # 显示服务
call SayHello # 调用方法
```
## 🧪 测试和调试
### 1. 查看 gRPC 流量
使用 **grpcui**:
```bash
# 安装
go install github.com/fullstorydev/grpcui/cmd/grpcui@latest
# 启动 Web UI
grpcui -plaintext localhost:50051
```
然后在浏览器中打开 `http://127.0.0.1:5757` 进行可视化测试。
### 2. 网络调试
```bash
# 查看端口监听
lsof -i :50051
# 测试连接
telnet localhost 50051
```
## ⚠️ 故障排除
| 问题 | 解决方案 |
|------|----------|
| `address already in use` | 更改端口或终止占用进程:
`lsof -i :50051` → `kill -9 ` |
| `connection refused` | 确保服务端已启动 |
| `no required module provides package` | 运行 `go mod tidy` |
| `protoc not found` | 安装 Protocol Buffers 编译器 |
| 插件未找到 | 确保 `$GOPATH/bin` 在 PATH 中 |
## 📚 学习资源
- [gRPC 官方文档](https://grpc.io/docs/languages/go/)
- [Protocol Buffers 指南](https://developers.google.com/protocol-buffers/docs/gotutorial)
- [Go gRPC 示例](https://github.com/grpc/grpc-go/tree/master/examples)
## 🎯 扩展功能
要扩展此项目,可以考虑:
1. **添加 TLS 加密**
```go
creds, _ := credentials.NewServerTLSFromFile("server.crt", "server.key")
s := grpc.NewServer(grpc.Creds(creds))
```
2. **添加拦截器(中间件)**
```go
s := grpc.NewServer(
grpc.UnaryInterceptor(loggingInterceptor),
)
```
3. **添加健康检查**
```go
import "google.golang.org/grpc/health"
healthServer := health.NewServer()
healthpb.RegisterHealthServer(s, healthServer)
```
4. **添加客户端负载均衡**
```go
conn, err := grpc.NewClient(
"dns:///my-service",
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`),
)
```
## 📄 许可证
此项目仅用于学习和演示目的。
## 🤝 贡献
欢迎提交 Issue 和 Pull Request!
---
**提示**:在生产环境中使用时应添加适当的错误处理、日志记录、监控和安全性措施。