# zeromile-framework **Repository Path**: teachitback/zeromile-framework ## Basic Information - **Project Name**: zeromile-framework - **Description**: zeromile-framework , service registration embedded with Zenoh communication infrastructure! - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-02-07 - **Last Updated**: 2026-02-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ZeroMile Framework (ZMF) > 基于 Zenoh 的分布式服务框架,提供简洁优雅的服务通信能力 [![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## 简介 ZeroMile Framework (ZMF) 是一个轻量级分布式服务框架,基于 [Zenoh](https://zenoh.io/) 构建,提供三种核心通信模式: ``` ┌─────────────────────────────────────────────────────────────┐ │ ZMF 核心架构 │ ├─────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Query │ │ Publish │ │ Subscribe │ │ │ │ 请求-响应 │ │ 发布事件 │ │ 订阅接收 │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ │ │ │ │ │ │ └──────────────────┼──────────────────┘ │ │ │ │ │ ┌────────┴────────┐ │ │ │ Zenoh Router │ │ │ │ (消息总线) │ │ │ └────────┬────────┘ │ │ │ │ │ ┌──────────────────┼──────────────────┐ │ │ │ │ │ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ┌──────┴──────┐ │ │ │ Service A │ │ Service B │ │ Service C │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │ │ └─────────────────────────────────────────────────────────────┘ ``` ## 三大核心 API | API | 模式 | 用途 | 代码示例 | |-----|------|------|----------| | `query()` | 请求-响应 | 同步调用服务 | `responses = server.query("service/method", data)` | | `publish()` | 发布-订阅 | 发送事件 | `server.publish("topic/event", data)` | | `subscribe()` | 订阅-接收 | 监听事件 | `server.subscribe("topic/event", callback)` | ## 双模式架构 ZMF 提供两种核心使用方式,适用于不同的应用场景: ### 1. ZMFServer - 完整框架服务端 **适用场景**:构建完整的微服务应用,需要服务注册、生命周期管理、组件依赖注入等。 **特点**: - 支持 Service 和 Component 注册 - 完整的生命周期管理 - 内置健康检查服务 - Zenoh 模式:`peer` 或 `router` ```python import zeromileframework as zmf # 使用 Fluent API 构建服务端 server = ( zmf.server_builder() .config("config.yaml") # 加载配置文件 .register_service(HelloService) # 注册服务 .register_component(DatabaseComponent) # 注册组件 .start() # 启动服务器 ) # 使用三大 API responses = server.query("hello/greet", {"name": "World"}) server.publish("topic/event", {"data": "value"}) server.subscribe("topic/event", callback) # 关闭服务器 server.shutdown() ``` ### 2. ZMFClient - 轻量级客户端 **适用场景**:只需要与现有 ZMF 服务通信的轻量级应用,无需服务注册。 **特点**: - 只提供三大 API:query、publish、subscribe - 无需启动完整框架 - 支持上下文管理器 - Zenoh 模式:`client` ```python from zeromileframework import ZMFClient # 方式 1: 使用配置文件 with ZMFClient.connect("config.yaml") as client: responses = client.query("service/method", {"key": "value"}) client.publish("topic/event", {"data": "value"}) # 方式 2: 直接指定配置(推荐,避免连接问题) client = ZMFClient.connect( mode="client", connect=["tcp/127.0.0.1:7447"] ) responses = client.query("hello/greet", {"name": "World"}) client.close() ``` ### 选择指南 | 需求 | 推荐 | Zenoh 模式 | |------|------|------------| | 需要定义和注册服务 | `ZMFServer` | `peer` 或 `router` | | 需要组件(数据库、缓存等) | `ZMFServer` | `peer` 或 `router` | | 需要健康检查 | `ZMFServer` | `peer` 或 `router` | | 只需要通信 API | `ZMFClient` | `client` | | 简单集成场景 | `ZMFClient` | `client` | ## 快速开始 ### 开发者安装(从源码) ```bash # 克隆仓库 git clone https://gitee.com/teachitback/zeromile-framework.git cd zeromile-framework # 安装开发版本(可编辑模式) pip install -e ".[dev]" # 运行测试验证安装 python -m pytest tests/ -v ``` ### 用户安装(从 PyPI) ```bash pip install zeromileframework ``` ## 使用示例 ### 1. 创建服务 ```python from zeromileframework import Service, BaseService, queryable, subscriber import time @Service("hello-service") class HelloService(BaseService): """ 问候服务 - 依赖 ZMF,可访问组件和通信能力 """ def __init__(self): super().__init__("hello-service") self._logger = None def configure(self, zmf) -> bool: """ 接收 ZMF 实例,可以: - 获取组件:zmf.get_component("name") - 获取配置:zmf.get_config() - 发布事件:zmf.publish(key, data) - 查询服务:zmf.query(key, payload) """ # 获取 logger 组件 self._logger = zmf.get_component("logger") return True def start(self) -> bool: if self._logger: self._logger.info("HelloService started") return True def stop(self) -> bool: return True def health(self) -> dict: return {"status": "healthy"} @queryable("hello/greet") def handle_greet(self, query: dict) -> dict: """响应问候查询""" name = query.get("name", "World") if self._logger: self._logger.info(f"Greeting {name}") return { "success": True, "message": f"Hello, {name}!", "timestamp": time.time() } @subscriber("hello/ping") def handle_ping(self, event: dict) -> None: """接收 ping,回复 pong""" # 通过 get_zmf() 获取 ZMF 实例发布事件 zmf = self.get_zmf() if zmf: zmf.publish("hello/pong", { "message": "pong from HelloService", "timestamp": time.time() }) ``` ### 2. 创建组件(可选) 组件提供基础设施能力(如数据库、缓存),供服务使用。 **Component vs Service 对比**: | 特性 | Component(组件) | Service(服务) | |------|------------------|----------------| | **职责** | 基础设施(数据库、日志、缓存) | 业务逻辑 | | **配置方式** | `configure(config: dict)` 只接收配置 | `configure(zmf)` 接收 ZMF 实例 | | **依赖关系** | 不依赖 ZMF,易于测试 | 依赖 ZMF,可访问组件和通信能力 | | **通信能力** | 不能直接发布/订阅 | 可以使用 `@queryable`/`@subscriber` | ```python from zeromileframework import Component, BaseComponent @Component("database") class DatabaseComponent(BaseComponent): """数据库组件 - 只依赖配置,不依赖 ZMF""" def __init__(self): super().__init__("database") self.connection = None def configure(self, config: dict): """ 只接收配置字典,不依赖 ZMF 实例 好处:解耦、易测试、单一职责 """ database_url = config.get("database_url") self.connection = create_db_connection(database_url) return True def start(self): """启动组件""" return self.connection is not None def stop(self): """停止组件""" if self.connection: self.connection.close() return True def health(self): """健康检查""" return { "status": "healthy" if self.connection else "disconnected", "component": self.component_name } def query(self, sql: str): """执行查询""" return self.connection.execute(sql).fetchall() ``` ### 3. 构建 ZMFServer 应用 ```python import zeromileframework as zmf # 使用 Fluent API 链式配置 server = ( zmf.server_builder() .config("config.yaml") .register_component(DatabaseComponent) # 注册组件(可选) .register_service(HelloService) # 注册服务 .start() ) # 使用三大 API import json responses = server.query("hello/greet", json.dumps({"name": "ZMF"})) if responses: print(responses[0]["message"]) # "Hello, ZMF!" # 关闭服务器 server.shutdown() ``` ### 4. 使用 ZMFClient 连接 ```python from zeromileframework import ZMFClient # 方式 1: 使用配置文件 with ZMFClient.connect("config.yaml") as client: responses = client.query("hello/greet", {"name": "World"}) if responses: print(responses[0]["message"]) # 方式 2: 直接指定配置(推荐) client = ZMFClient.connect( mode="client", connect=["tcp/127.0.0.1:7447"] ) responses = client.query("hello/greet", {"name": "World"}) client.close() ``` ## 完整示例 ### 运行示例应用 ```bash # 进入示例目录 cd examples/hello-app # 运行 Hello App 示例 python src/hello_app/main.py ``` ### 输出示例 ``` ====================================================================== ZMF Core API Demonstration ====================================================================== [API 1] query() - Request/Response Pattern ---------------------------------------------------------------------- → Querying 'hello/greet'... ✓ Response: Hello, World! [API 2 & 3] publish() & subscribe() - Pub/Sub Pattern ---------------------------------------------------------------------- → Publishing 'hello/ping'... ✓ Ping sent [hello-service] Got ping [hello-service] Published pong ✓ Main got pong: pong from HelloService ``` ## 项目结构 ``` zeromile-framework/ ├── src/zeromileframework/ # 框架核心代码 │ ├── __init__.py # 导出核心 API │ ├── server.py # ZMFServer 服务端 │ ├── client.py # ZMFClient 轻量级客户端 │ ├── zenoh_session.py # 共享 Zenoh 会话管理 │ ├── decorators.py # @Service, @queryable, @subscriber │ ├── components/ # 内置组件 │ └── services/ # 内置服务 │ └── health_service.py ├── examples/ # 示例应用 │ ├── hello-app/ # 入门示例(三大 API) │ └── fastapi-zmf-example/ # FastAPI 集成示例 ├── tests/ # 测试 ├── FRAMEWORK_DESIGN.md # 架构设计文档 └── README.md # 本文档 ``` ## 核心特性 ### 1. 简洁的 Fluent API ```python server = ( zmf.server_builder() .config("config.yaml") .register_service(MyService) .register_component(DatabaseComponent) .start() ) ``` ### 2. 装饰器驱动开发 ```python @Service("user-service") # 服务注册 @queryable("user/get") # 可查询端点 @subscriber("user/events") # 事件订阅 ``` ### 3. 服务生命周期管理 ```python def start(self) -> bool: # 服务启动 def stop(self) -> bool: # 服务停止 def health(self) -> dict: # 健康检查 ``` ### 4. 内置健康检查 ```bash curl http://localhost:8000/health ``` ```json { "status": "healthy", "framework": "ZMF", "zmf": { "status": "running", "logger_available": true }, "services": { "count": 2, "healthy": 2, "details": [ { "name": "hello-service", "status": "healthy", "running": true } ] }, "components": { "count": 1, "ready": 1, "details": [ { "name": "LoggerComponent", "status": "ready" } ] } } ``` ## 示例应用 | 示例 | 说明 | 路径 | |------|------|------| | Hello App | 入门示例,演示三大 API | `examples/hello-app/` | | FastAPI ZMF | FastAPI 集成示例 | `examples/fastapi-zmf-example/` | ## 架构设计 ``` ┌─────────────────────────────────────────────────────────────┐ │ Application Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ Service │ │ Service │ │ Component │ │ │ │ A │ │ B │ │ (Database) │ │ │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │ └─────────┼────────────────┼────────────────┼────────────────┘ │ │ │ └────────────────┼────────────────┘ │ ┌──────────────────────────┼──────────────────────────────────┐ │ ZMF Core Layer │ │ ┌───────────────────────┴───────────────────────┐ │ │ │ ZMFServer / ZMFClient │ │ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ │ │ Query │ │ Publish │ │ Subscribe│ │ │ │ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ └───────┼─────────────┼─────────────┼──────────┘ │ └──────────┼─────────────┼─────────────┼─────────────────────┘ │ │ │ └─────────────┼─────────────┘ │ ┌────────────────────────┼────────────────────────────────────┐ │ Zenoh Layer │ │ (Distributed Message Bus) │ └─────────────────────────────────────────────────────────────┘ ``` ## 文档 - [快速入门](examples/hello-app/README.md) - 学习三大核心 API - [架构设计](FRAMEWORK_DESIGN.md) - 深入了解框架设计 - [FastAPI 集成](examples/fastapi-zmf-example/README.md) - Web 服务集成 ## 开发指南 ### 环境准备 ```bash # 克隆仓库 git clone https://gitee.com/teachitback/zeromile-framework.git cd zeromile-framework # 创建虚拟环境(推荐) python -m venv venv source venv/bin/activate # Linux/Mac # 或: venv\Scripts\activate # Windows # 安装开发依赖 pip install -e ".[dev]" ``` ### 常用命令 ```bash # 运行所有测试 python -m pytest tests/ -v # 运行特定测试 python -m pytest tests/test_builder.py -v # 代码检查 ruff check src/ # 类型检查 python -m zeromileframework.scripts.type_check ``` ## 贡献 欢迎提交 Issue 和 PR! ## 许可证 MIT License - 详见 [LICENSE](LICENSE) 文件 ## 配置文件说明 ### 配置文件示例 ```yaml # Zenoh 配置 zenoh: mode: "peer" # peer, router, 或 client listen: ["tcp/0.0.0.0:7447"] # 监听地址(server 模式) connect: ["tcp/127.0.0.1:7447"] # 连接地址(client 模式) timeout: 5.0 # 日志配置 logging: level: "INFO" format: "[%(asctime)s] [%(levelname)s] %(message)s" # 数据库配置 database: url: "postgresql://localhost/mydb" pool_size: 10 # 服务配置 user-service: timeout: 30 retry_count: 3 ``` ### 配置加载方式 **ZMFServer 加载配置**: ```python # 方式1:配置文件 server = zmf.server_builder().config("config.yaml").start() # 方式2:字典配置 server = zmf.server_builder().config({ "zenoh": {"mode": "peer", "listen": ["tcp/0.0.0.0:7447"]} }).start() ``` **ZMFClient 加载配置**: ```python # 方式1:配置文件 client = ZMFClient.connect("config.yaml") # 方式2:字典配置 client = ZMFClient.connect({ "mode": "client", "connect": ["tcp/127.0.0.1:7447"] }) # 方式3:直接参数(推荐) client = ZMFClient.connect(mode="client", connect=["tcp/127.0.0.1:7447"]) ``` ## 故障排除 ### ZMFClient 连接问题 **问题:连接超时或无响应** ```python # 解决方案:明确指定连接参数 client = ZMFClient.connect( mode="client", connect=["tcp/127.0.0.1:7447"], # 确保端口与 ZMFServer 一致 timeout=10.0 # 增加超时时间 ) ``` **问题:Mode 配置错误** ```python # ❌ 错误:ZMFClient 不能使用 peer 模式 client = ZMFClient.connect(mode="peer") # 会报错 # ✅ 正确:ZMFClient 必须使用 client 模式 client = ZMFClient.connect(mode="client") ``` ### ZMFServer 启动问题 **问题:端口冲突** ```yaml # 解决方案:修改监听端口 zenoh: mode: "peer" listen: ["tcp/0.0.0.0:7555"] # 改为其他端口 ``` **问题:服务发现失败** - 确保 ZMFServer 和 ZMFClient 使用相同的 Zenoh 配置 - 检查防火墙设置,确保端口可访问 - 验证 `zenohd` 是否正在运行(如果使用) ## 参考 - [Zenoh 官网](https://zenoh.io/) - [Eclipse Zenoh](https://github.com/eclipse-zenoh/zenoh) --- **ZeroMile Framework** - 让分布式服务开发更简单