Files
z-docs/docs/tutorial-basics/broadcast-delay.md

113 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.

---
sidebar_position: 3
title: 广播与延时消息
description: ZHub 广播消息和延时消息功能详解,包含基础使用、应用场景和注意事项
---
# 广播与延时消息
## 广播消息
广播消息发送给所有连接的客户端。
### 基础使用
**字符串广播**
```java
// 发送广播
zhub.broadcast("topic-abc", "hello!");
// 订阅广播
zhub.subscribe("topic-abc", message -> {
System.out.println("收到公告: " + message);
});
```
**类型化广播**
```java
// 定义通知类型
public class SystemNotification {
private String type;
private String title;
private String content;
private long timestamp;
// getter/setter...
}
// 发送类型化广播
SystemNotification notification = new SystemNotification(
"maintenance", "hello!", "hello!", System.currentTimeMillis()
);
zhub.broadcast("topic-abc", notification);
// 订阅类型化广播
zhub.subscribe("topic-abc", new TypeToken<SystemNotification>(){}, notification -> {
System.out.println("通知: " + notification.getTitle());
});
```
### 应用场景
**示例场景**
```java
zhub.broadcast("topic-abc", "hello!");
zhub.broadcast("topic-def", "hello!");
```
**配置更新**
```java
zhub.broadcast("topic-xyz", "hello!");
zhub.subscribe("topic-xyz", message -> updateConfig(message));
```
**状态同步**
```java
zhub.broadcast("topic-123", "hello!");
zhub.subscribe("topic-123", message -> System.out.println("状态: " + message));
```
---
## 延时消息
延时消息在指定时间后发送,支持毫秒级精度。
### 基础使用
```java
// 延时5秒
zhub.delay("reminder-task", "执行提醒任务", 5000);
// 延时1小时
zhub.delay("cleanup-task", "执行清理任务", 60 * 60 * 1000);
// 延时1天
zhub.delay("report-generate", "生成日报", 24 * 60 * 60 * 1000);
```
### 应用场景
**任务提醒**
```java
zhub.delay("task-reminder", "任务即将到期", 5 * 60 * 1000);
zhub.subscribe("task-reminder", message -> sendReminder(message));
```
**订单超时**
```java
zhub.delay("order-timeout-check", orderId, 30 * 60 * 1000);
zhub.subscribe("order-timeout-check", orderId -> checkOrderTimeout(orderId));
```
**缓存过期**
```java
zhub.delay("cache-expire", key, expireMs);
zhub.subscribe("cache-expire", key -> cache.remove(key));
```
## 注意事项
- 延时时间不限制延迟时间
- 重启后延时消息丢失
- 广播消息影响所有客户端性能