Files
chongming-utils-request/README.md
T
2026-08-05 18:21:21 +08:00

85 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# chongming-request
Zenoh Worker 直连客户端,用于从服务端或其他 Worker 直接调用 Zenoh RPC,无需经过 HTTP 路由。
---
## 安装
```bash
uv pip install -e utils/request
```
---
## 功能
- **自动服务发现**:基于 Zenoh liveliness 自动发现存活的 Worker
- **随机负载均衡**:在可用 Worker 间随机选择
- **超时重试**:请求超时后自动重试
- **同步/异步支持**:提供 `call`(异步)和 `call_sync`(同步)接口
---
## API
### `Client` 类
```python
from chongming_request import Client
async with Client(session=zenoh_session) as client:
result = await client.call(
worker_type="example",
subject="example.add",
payload={"a": 1, "b": 2},
method="GET"
)
```
| 参数 | 类型 | 说明 |
| ------------- | --------------- | -------------------------------- |
| `session` | `zenoh.Session` | Zenoh 会话对象 |
| `worker_type` | `str` | Worker 类型名(如 `"example"`) |
| `subject` | `str` | Zenoh 主题(如 `"example.add"`) |
| `payload` | `dict` | 调用载荷 |
| `method` | `str` | HTTP 方法(`"GET"` / `"POST"`) |
| `timeout` | `float` | 超时时间(秒) |
### 同步调用
```python
result = client.call_sync(
worker_type="example",
subject="example.add",
payload={"a": 1, "b": 2},
timeout=5.0
)
```
---
## 使用场景
1. **Worker 间互相调用**:一个 Worker 调用另一个 Worker 的 RPC 方法
2. **服务端内部调用**:在 FastAPI 路由处理器中直接调用 Worker
3. **内部接口调用**:调用 `internal = true` 的端点(不暴露 HTTP 路由)
4. **测试与调试**:直接测试 Worker 的 RPC 行为
---
## 与 HTTP 调用的对比
| 特性 | HTTP 调用 | `chongming-request` |
| -------------------- | ------------------ | -------------------- |
| 需要注册 HTTP 路由 | ✅ | ❌(直接 Zenoh RPC) |
| 支持 `internal` 端点 | ❌ | ✅ |
| 序列化开销 | JSON → HTTP → JSON | JSON → Zenoh → JSON |
| 适用场景 | 外部客户端 | 内部微服务通信 |
---
## 依赖
- `zenoh` — Zenoh Python 绑定(`eclipse-zenoh`)