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