Files
z-docs/docs/tutorial-extras/api-reference.md

149 lines
2.5 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.

---
sidebar_position: 1
title: API 参考
description: ZHub 完整 API 参考文档
---
# API 参考
ZHub 客户端和管理接口的完整参考。
## 客户端 API
### 创建连接
```java
// 基础连接
ZHubClient zhub = new ZHubClient("127.0.0.1:1216", "group1", "app1");
// 带认证连接
ZHubClient zhub = new ZHubClient("127.0.0.1:1216", "group1", "app1", "token123");
```
**参数**
- `addr`: 服务地址 `IP:端口`
- `groupId`: 组名
- `appId`: 应用ID唯一
- `auth`: 认证码(可选)
### 消息操作
#### 发布订阅
```java
// 发布消息
zhub.publish("user.login", "用户登录");
// 订阅消息
zhub.subscribe("user.login", message -> {
System.out.println("收到: " + message);
});
```
#### 广播消息
```java
// 广播给所有客户端
zhub.broadcast("topic-abc", "hello!");
```
#### 延时消息
```java
// 30秒后发送
zhub.delay("order.timeout", "订单超时", 30000);
```
### RPC 调用
#### 提供服务
```java
// 提供 RPC 服务
zhub.rpcSubscribe("user.getInfo", IType.STRING, request -> {
String userId = request.getValue();
return request.render("用户信息: " + userId);
});
```
#### 调用服务
```java
// 调用 RPC 服务
RpcResult<String> result = zhub.rpc("user.getInfo", "user123", IType.STRING);
if (result.isSuccess()) {
System.out.println("结果: " + result.getResult());
}
```
### 定时任务
```java
// 订阅定时任务
zhub.timer("T:A", () -> {
System.out.println("定时执行");
});
```
### 分布式锁
```java
// 获取锁
Lock lock = zhub.tryLock("resource-key", 30);
if (lock.success()) {
try {
// 执行业务逻辑
} finally {
lock.unLock();
}
}
```
---
## 管理接口
### 查看服务状态
```bash
# 查看服务信息
curl http://127.0.0.1:711/_/info
# 查看版本
curl http://127.0.0.1:711/_/version
```
### 管理操作
```bash
# 清理内存
curl http://127.0.0.1:711/_/cleanup
# 重载定时任务
curl http://127.0.0.1:711/timer/reload
# 重载权限配置
curl http://127.0.0.1:711/auth/reload
```
### 发送消息
```bash
# 发布消息
curl -X POST http://127.0.0.1:711/message/send \
-d "type=publish&name=user.login&value=用户登录"
```
---
## 常用类型
### IType 类型
```java
IType.STRING // 字符串
IType.INT // 整数
IType.LONG // 长整数
IType.DOUBLE // 浮点数
IType.MAP // 键值对
```
### 错误码
| 错误码 | 说明 |
|--------|------|
| 0 | 成功 |
| 501 | 请求失败 |
| 505 | 请求超时 |
| 401 | 认证失败 |