Mercure 即時推播
Doggy 基於 Mercure 協定實作伺服器端即時推播。Mercure Hub 內建於 FrankenPHP,透過 Caddyfile 設定即可啟用,無需額外容器或服務。
架構
客户端 (EventSource)
↑ SSE
└── http://localhost:8000/.well-known/mercure
↑
Caddyfile (FrankenPHP)
↑ mercure 指令内嵌 Hub
FrankenPHP (内置 Hub)Caddyfile 設定
FrankenPHP 的 Caddyfile 中嵌入 Mercure Hub:
caddy
http://localhost:8000 {
route /.well-known/mercure {
mercure {
transport bolt {
path /var/www/var/mercure.db
}
publisher_jwt !ChangeThisMercureHubJWTSecretKey!
subscriber_jwt !ChangeThisMercureHubJWTSecretKey!
cors_origins http://localhost:8000
publish_origins *
anonymous
}
}
}JWT 權杖
MercureTokenFactory 產生帶訂閱權限的 JWT:
php
// src/Security/MercureTokenFactory.php
$token = $factory->createSubscribeToken(
topics: ['/user/123/*', '/entity/*'],
roles: ['ROLE_USER'],
expiresIn: 3600
);Mercure Cookie
MercureCookieSubscriber 在每個回應中注入 mercureAuthorization Cookie:
php
// 自动生成的订阅主题
$topics = [
'https://enterprise.local/user/' . $userId . '/export',
'/user/' . $userId . '/*',
'/entity/*',
];前端訂閱
javascript
const url = new URL('/.well-known/mercure', window.location.origin);
url.searchParams.append('topic', '/user/' + userId + '/*');
const eventSource = new EventSource(url);
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
// 处理推送消息
};核心應用
- 匯出進度:大型檔案匯出即時進度推播
- 線上狀態:
PresenceService+PresenceApiController - 即時通知:系統訊息、審批提醒
- 資料同步:多使用者協作即時更新