30 lines
703 B
Rust
30 lines
703 B
Rust
use crate::models::ServerEvent;
|
|
use once_cell::sync::Lazy;
|
|
use tokio::sync::broadcast;
|
|
|
|
/// SSE 事件管理器
|
|
pub struct EventManager {
|
|
tx: broadcast::Sender<String>,
|
|
}
|
|
|
|
impl EventManager {
|
|
pub fn new() -> Self {
|
|
let (tx, _) = broadcast::channel(64);
|
|
Self { tx }
|
|
}
|
|
|
|
/// 广播事件给所有 SSE 客户端
|
|
pub fn broadcast(&self, event: &ServerEvent) {
|
|
if let Ok(json) = serde_json::to_string(event) {
|
|
let _ = self.tx.send(json);
|
|
}
|
|
}
|
|
|
|
/// 获取广播接收器
|
|
pub fn subscribe(&self) -> broadcast::Receiver<String> {
|
|
self.tx.subscribe()
|
|
}
|
|
}
|
|
|
|
pub static EVENTS: Lazy<EventManager> = Lazy::new(EventManager::new);
|