# WebmanGRPC **Repository Path**: endcms/webman-grpc ## Basic Information - **Project Name**: WebmanGRPC - **Description**: No description available - **Primary Language**: PHP - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-10-14 - **Last Updated**: 2025-10-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Webman gRPC扩展包 [![Latest Stable Version](https://poser.pugx.org/endcms/webman-grpc/v/stable)](https://packagist.org/packages/endcms/webman-grpc) [![License](https://poser.pugx.org/endcms/webman-grpc/license)](https://packagist.org/packages/endcms/webman-grpc) [![PHP Version Require](https://poser.pugx.org/endcms/webman-grpc/require/php)](https://packagist.org/packages/endcms/webman-grpc) ## 介绍 Webman gRPC扩展包是一个深度适配集成Webman框架的gRPC解决方案,提供便捷的gRPC服务端/客户端创建与通信功能,以及HTTP请求与gRPC请求转换功能。 该扩展包基于PHP官方gRPC扩展开发,支持简单调用、流式调用和双向流调用,同时提供了丰富的拦截器机制和转换器接口,方便开发者进行功能扩展和定制。 ## 特性 - 🚀 **高性能**:基于PHP官方gRPC扩展,提供高性能的gRPC服务 - 🔌 **深度集成**:完美集成Webman框架,支持进程管理和配置管理 - 🛡️ **安全可靠**:支持SSL/TLS加密通信,保障数据传输安全 - 🔄 **双向通信**:支持简单调用、服务端流、客户端流和双向流调用 - 🌐 **HTTP网关**:提供HTTP到gRPC的转换功能,方便Web应用调用gRPC服务 - 🔧 **易于扩展**:提供拦截器和转换器接口,方便功能扩展 - 📊 **连接池**:客户端支持连接池管理,提高性能 - 🔄 **自动重试**:客户端支持自动重试和退避策略 - ⚖️ **负载均衡**:客户端支持多种负载均衡策略 - 📝 **完整文档**:提供详细的文档和示例代码 - 🔍 **性能监控**:提供全面的性能监控和统计功能 - 🧩 **模块化设计**:支持模块化开发和插件化架构 - ⚡ **序列化优化**:提供消息对象池和序列化缓存 - 🧠 **内存管理**:提供内存使用监控和自动释放机制 - 🎯 **事件驱动**:支持事件总线和生命周期钩子 ## 安装 使用Composer安装: ```bash composer require endcms/webman-grpc ``` ## 快速开始 ### 1. 配置 在`config/plugin/endcms/webman-grpc/app.php`中配置gRPC服务: ```php true, // gRPC配置 'grpc' => [ // 启用gRPC 'enabled' => true, // 服务端配置 'server' => [ 'host' => '0.0.0.0', 'port' => 50051, 'credentials' => null, // SSL凭证 ], // 客户端配置 'client' => [ 'timeout' => 30, // 超时时间(秒) 'credentials' => null, // SSL凭证 'retry' => 3, // 重试次数 ], // 连接池配置 'connection_pool' => [ 'max_connections' => 10, 'max_lifetime' => 300, // 5分钟 'health_check_interval' => 30, // 30秒 'health_check_timeout' => 5, // 5秒 'leak_detection_interval' => 60, // 60秒 'leak_detection_threshold' => 300, // 5分钟 'warm_up_connections' => 2, ], // 序列化配置 'serialization' => [ 'lite_mode' => false, 'pool_enabled' => true, 'cache_enabled' => true, 'pool_config' => [ 'max_size' => 100, 'min_size' => 5, ], 'cache_size' => 1000, ], // 内存管理配置 'memory' => [ 'memory_limit' => 0, // 0表示使用PHP配置的限制 'warning_threshold' => 0, // 0表示为限制的80% 'max_history_size' => 100, 'monitoring_enabled' => false, 'monitoring_interval' => 5, ], // 流式处理配置 'stream_processor' => [ 'max_memory_usage' => 50 * 1024 * 1024, // 50MB 'batch_size' => 100, 'memory_monitoring_enabled' => true, ], // 事件配置 'event' => [ 'history_enabled' => false, 'max_history_size' => 100, ], // 预热配置 'warm_up' => [ 'addresses' => [ '127.0.0.1:50051', ], 'options' => [ 'credentials' => \Grpc\ChannelCredentials::createInsecure(), ], 'message_classes' => [ // 预热的消息类列表 ], ], // 注册的服务 'services' => [ 'example.ExampleService' => [ 'class' => \WebmanGrpc\Examples\ExampleService::class, 'options' => [], ], ], ], ]; ``` ### 2. 创建gRPC服务 ```php setMessage('Hello ' . $request->getName()); return $response; } } ``` ### 3. 使用gRPC客户端 ```php \Grpc\ChannelCredentials::createInsecure(), ]); // 调用方法 $request = new Helloworld\HelloRequest(); $request->setName('World'); $response = $client->call('SayHello', $request); // 流式调用 $stream = $client->stream('ServerStream', $request); foreach ($stream->responses() as $response) { // 处理响应 } // 关闭客户端 $client->close(); ``` ### 4. 获取统计信息 ```php use WebmanGrpc\Client\GrpcClient; // 获取连接池统计 $poolStats = GrpcClient::getConnectionPoolStats(); // 获取序列化统计 $serializationStats = GrpcClient::getSerializationStats(); // 获取性能数据 $performanceData = GrpcClient::getPerformanceData(); // 生成性能报告 $report = GrpcClient::generatePerformanceReport(); ``` ### 5. 使用gRPC管理器 ```php use WebmanGrpc\GrpcManager; // 获取管理器实例 $manager = GrpcManager::getInstance(); // 预热连接 $manager->warmUpConnections(['127.0.0.1:50051']); // 预热序列化 $manager->warmUpSerialization([ \Helloworld\HelloRequest::class, \Helloworld\HelloReply::class, ]); // 获取统计信息 $stats = $manager->getStats(); // 生成性能报告 $report = $manager->generatePerformanceReport(); ``` ### 6. 启动服务 ```bash php start.php start ``` ### 7. 测试服务 使用grpcurl测试gRPC服务: ```bash grpcurl -plaintext -d '{"name":"World"}' localhost:50051 example.ExampleService/SimpleMethod ``` 使用curl测试HTTP网关: ```bash curl -X POST -H 'Content-Type: application/json' -d '{"name":"World"}' http://localhost:8787/api/example/simple ``` ## 详细文档 ### 服务端 #### 创建服务 继承`BaseService`类创建gRPC服务: ```php setMessage('Hello ' . $request->getName()); return $response; } } ``` #### 注册服务 在配置文件中注册服务: ```php 'services' => [ 'my.MyService' => [ 'class' => \App\Service\MyService::class, 'options' => [], ], ], ``` #### 拦截器 实现`ServerInterceptorInterface`接口创建拦截器: ```php [ [ 'class' => \App\Interceptor\MyInterceptor::class, 'priority' => 100, ], ], ``` ### 客户端 #### 创建客户端 ```php 'localhost', 'port' => 50051, ]); // 简单调用 $request = new ExampleRequest(); $request->setName('World'); $response = $client->simpleCall('example.ExampleService', 'SimpleMethod', $request); echo $response->getMessage() . "\n"; ``` #### 流式调用 ```php // 服务端流 $client->serverStream('example.ExampleService', 'StreamMethod', $request, function($response) { echo $response->getMessage() . "\n"; }); // 双向流 $stream = $client->bidirectionalStream('example.ExampleService', 'BidirectionalStream'); $stream->write($request1); $stream->write($request2); while ($response = $stream->read()) { echo $response->getMessage() . "\n"; } $stream->close(); ``` ### HTTP网关 #### 配置路由 在配置文件中配置HTTP到gRPC的路由: ```php 'http_gateway' => [ 'enabled' => true, 'routes' => [ [ 'path' => '/api/example/simple', 'method' => 'POST', 'service' => 'example.ExampleService', 'method' => 'SimpleMethod', 'request_transformer' => \App\Transformer\MyRequestTransformer::class, 'response_transformer' => \App\Transformer\MyResponseTransformer::class, 'address' => '127.0.0.1:50051', ], ], ], ``` #### 创建转换器 实现请求转换器: ```php rawBody(), true); $request = new ExampleRequest(); $request->setName($data['name'] ?? 'World'); return $request; } } ``` 实现响应转换器: ```php $grpcResponse->getMessage(), 'code' => 0, 'success' => true, ]; return new Response(200, [ 'Content-Type' => 'application/json' ], json_encode($data)); } } ``` ### 模块化设计 #### 自定义模块 ```php use WebmanGrpc\Module\BaseModule; class MyModule extends BaseModule { public function getName(): string { return 'my_module'; } public function getVersion(): string { return '1.0.0'; } public function getDependencies(): array { return []; } public function initialize(): bool { // 初始化逻辑 return true; } public function start(): bool { // 启动逻辑 return true; } public function stop(): bool { // 停止逻辑 return true; } } // 注册模块 $moduleManager = $manager->getModuleManager(); $moduleManager->register(new MyModule()); ``` ### 事件驱动架构 #### 事件监听 ```php use WebmanGrpc\Event\EventBus; use WebmanGrpc\Event\EventListenerInterface; class MyEventListener implements EventListenerInterface { public function handle($event): void { // 处理事件 echo "Event {$event->getName()} received with data: " . json_encode($event->getData()); } public function getPriority(): int { return 100; } } // 添加事件监听器 $eventBus = $manager->getEventBus(); $eventBus->addListener('my_event', new MyEventListener()); // 发布事件 $event = new \WebmanGrpc\Event\Event('my_event', ['key' => 'value']); $eventBus->publish($event); ``` #### 生命周期钩子 ```php use WebmanGrpc\Event\LifecycleEventManager; $lifecycleEventManager = $manager->getLifecycleEventManager(); // 添加启动钩子 $lifecycleEventManager->addHook('startup', function () { echo "Application started"; }); // 添加关闭钩子 $lifecycleEventManager->addHook('shutdown', function () { echo "Application shutdown"; }); ``` ## 性能优化 ### 连接池优化 1. **调整连接池大小**:根据应用负载调整连接池大小 2. **启用连接预热**:在应用启动时预热常用连接 3. **配置健康检查**:定期检查连接有效性,自动清理无效连接 4. **启用泄漏检测**:自动检测和回收长时间未使用的连接 ### 序列化优化 1. **启用对象池**:减少频繁创建/销毁Protobuf消息对象的开销 2. **启用序列化缓存**:对常用消息进行缓存,提高序列化性能 3. **使用Lite模式**:对简单消息使用Lite模式,减少序列化开销 ### 内存管理优化 1. **设置内存限制**:根据应用需求设置合理的内存限制 2. **启用内存监控**:实时监控内存使用情况,设置警告阈值 3. **使用流式处理**:处理大量数据时使用流式处理,避免大消息全部加载到内存 ### 其他优化 1. **启用性能监控**:定期检查性能报告,优化瓶颈 2. **使用事件驱动**:通过事件总线解耦组件,提高可维护性 3. **模块化设计**:将功能拆分为模块,降低耦合度,提高可扩展性 ## 配置选项 ### 服务端配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | host | string | 0.0.0.0 | 监听地址 | | port | int | 50051 | 监听端口 | | credentials | mixed | null | SSL凭证 | | max_recv_msg_length | int | 4194304 | 最大接收消息长度(字节) | | max_send_msg_length | int | 4194304 | 最大发送消息长度(字节) | ### 客户端配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | timeout | int | 30 | 超时时间(秒) | | credentials | mixed | null | SSL凭证 | | max_recv_msg_length | int | 4194304 | 最大接收消息长度(字节) | | max_send_msg_length | int | 4194304 | 最大发送消息长度(字节) | | retry | int | 3 | 重试次数 | | backoff | array | [] | 退避策略 | | connection_pool | array | [] | 连接池配置 | ### 连接池配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | max_connections | int | 10 | 最大连接数 | | max_lifetime | int | 300 | 连接最大生存时间(秒) | | health_check_interval | int | 30 | 健康检查间隔(秒) | | health_check_timeout | int | 5 | 健康检查超时(秒) | | leak_detection_interval | int | 60 | 泄漏检测间隔(秒) | | leak_detection_threshold | int | 300 | 泄漏检测阈值(秒) | | warm_up_connections | int | 2 | 预热连接数 | ### 序列化配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | lite_mode | bool | false | 是否启用Lite模式 | | pool_enabled | bool | true | 是否启用对象池 | | cache_enabled | bool | true | 是否启用序列化缓存 | | pool_config | array | [] | 对象池配置 | | cache_size | int | 1000 | 缓存大小 | ### 内存管理配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | memory_limit | int | 0 | 内存限制(字节),0表示使用PHP配置的限制 | | warning_threshold | int | 0 | 警告阈值(字节),0表示为限制的80% | | max_history_size | int | 100 | 最大历史记录数 | | monitoring_enabled | bool | false | 是否启用内存监控 | | monitoring_interval | int | 5 | 监控间隔(秒) | ### 流式处理配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | max_memory_usage | int | 52428800 | 最大内存使用量(字节) | | batch_size | int | 100 | 批处理大小 | | memory_monitoring_enabled | bool | true | 是否启用内存监控 | ### 事件配置 | 选项 | 类型 | 默认值 | 说明 | |------|------|--------|------| | history_enabled | bool | false | 是否启用事件历史记录 | | max_history_size | int | 100 | 最大历史记录数 | ## 故障排除 ### 常见问题 1. **gRPC扩展未安装** - 确保已安装PHP gRPC扩展 - 安装命令:`pecl install grpc` 2. **protobuf扩展未安装** - 确保已安装PHP protobuf扩展 - 安装命令:`pecl install protobuf` 3. **连接被拒绝** - 检查服务端是否已启动 - 检查防火墙设置 - 确认端口未被占用 4. **SSL证书错误** - 检查证书路径是否正确 - 确认证书格式是否正确 - 检查证书是否过期 5. **内存使用过高** - 检查是否启用了内存监控 - 调整内存限制和警告阈值 - 优化流式处理配置 6. **性能问题** - 检查连接池配置是否合理 - 启用序列化优化 - 查看性能报告,定位瓶颈 ## 参与贡献 欢迎提交Issue和Pull Request来帮助改进这个项目。 1. Fork 本仓库 2. 创建特性分支 (`git checkout -b feature/AmazingFeature`) 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`) 4. 推送到分支 (`git push origin feature/AmazingFeature`) 5. 打开Pull Request ## 许可证 本项目采用MIT许可证。详情请参阅[LICENSE](LICENSE)文件。 ## 更新日志 详情请参阅[CHANGELOG.md](CHANGELOG.md)文件。