# mongo-proxy **Repository Path**: kanin99/mongo-proxy ## Basic Information - **Project Name**: mongo-proxy - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-04-14 - **Last Updated**: 2026-04-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## MongoDB 代理 基于 独立 gRPC 微服务 的 MongoDB 客户端 ## 整体架构设计 ``` ┌─────────────────────────────────────────────────────────────┐ │ PHP (Hyperf) 应用层 │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ MongoDB Client Wrapper │ │ │ │ - 读取配置 filesystems.mongodb.connections │ │ │ │ - 提供简洁的调用接口 │ │ │ └─────────────────────────────────────────────────────┘ │ │ │ │ │ gRPC / HTTP 调用 │ └────────────────────────────┼────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ Go MongoDB Proxy Service (独立部署) │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Client A │ │ Client B │ │ Client C │ │ │ │ (业务库) │ │ (日志库) │ │ (缓存库) │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ MongoDB A MongoDB B MongoDB C │ └─────────────────────────────────────────────────────────────┘ ``` ## 一、项目结构 1.1 项目结构 ``` mongo-proxy/ ├── main.go ├── config/ │ └── config.go # 配置结构定义 ├── pool/ │ └── manager.go # 多客户端连接池管理 ├── handler/ │ └── mongo_handler.go # gRPC 服务实现 ├── proto/ │ └── mongo.proto # gRPC 协议定义 └── config.yaml # 服务配置文件 ``` 1.2 配置文件设计 (config.yaml) ```yaml server: addr: ":9001" # gRPC 监听地址 mongodb: connections: # 默认连接 default: uri: "mongodb://localhost:27017" connect_timeout: 3s read_timeout: 10s max_pool_size: 100 # 业务库 business: uri: "mongodb://user:pass@business-host:27017/business_db" connect_timeout: 5s read_timeout: 30s max_pool_size: 200 # 日志库 log: uri: "mongodb://user:pass@log-host:27017/log_db" connect_timeout: 3s read_timeout: 5s max_pool_size: 50 # 缓存库 cache: uri: "mongodb://user:pass@cache-host:27017/cache_db" connect_timeout: 2s read_timeout: 3s max_pool_size: 150 ``` ## protobuf 的使用 ### 1. 安装必要的 Go 插件 需要用 Go 的包管理工具来安装两个插件: - protoc-gen-go:负责生成 .pb.go 文件,里面是消息结构体的定义。 - protoc-gen-go-grpc:负责生成 _grpc.pb.go 文件,里面是 gRPC 服务的客户端和服务端接口。 打开终端执行以下命令: ```shell go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest ``` 小提示:请确保 $GOPATH/bin 已经加入系统的 PATH 环境变量,这样 protoc 才能找到插件。 ### 2. 执行编译命令 安装好插件后,进入 mongo.proto 文件所在的目录,执行下面的命令就能生成 Go 代码了: ````shell protoc --go_out=. --go-grpc_out=. mongo.proto ```` #### 参数解释: - --go_out=.:指定 .pb.go 消息文件在当前目录生成。 - --go-grpc_out=.:指定 _grpc.pb.go 服务文件在当前目录生成。