排除事件接收者
如果客户端在服务器发布变更之前乐观地应用了该变更,收到同一事件会导致变更被重复应用。这可能引起闪烁或重复项。
传入发起操作的客户端的连接 ID,即可将事件投递给其他所有已订阅的连接。
await bird.realtime.publish(appId, {
event: "message.created",
channels: ["presence-room-1"],
data: { body: "hello" },
exclude_connection_id: "26896.319537",
});client.realtime.publish(
app_id,
event="message.created",
channels=["presence-room-1"],
data={"body": "hello"},
exclude_connection_id="26896.319537",
)_, err := client.Realtime.Publish(context.Background(), appID, bird.RealtimePublishParams{
Event: "message.created",
Channels: []string{"presence-room-1"},
Data: map[string]any{"body": "hello"},
ExcludeConnectionID: "26896.319537",
})$bird->realtime->publish($appId, (new RealtimePublish())
->setEvent('message.created')
->setChannels(['presence-room-1'])
->setData(['body' => 'hello'])
->setExcludeConnectionId('26896.319537'));获取连接 ID
客户端读取自身的连接 ID,并在触发变更的请求中一同发送:
const bird = new BirdRealtime({ appKey: "your-app-key", region: "us1" });
await fetch("/messages", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
body: "hello",
connection_id: bird.connection.connectionId,
}),
});let bird = BirdRealtime(options: .init(appKey: "your-app-key", region: "us1"))
var request = URLRequest(url: URL(string: "https://your-backend.example.com/messages")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "content-type")
request.httpBody = try JSONSerialization.data(withJSONObject: [
"body": "hello",
"connection_id": bird.connectionId ?? "",
])
_ = try await URLSession.shared.data(for: request)val bird = BirdRealtime(BirdRealtimeOptions(appKey = "your-app-key", region = "us1"))
// Send the client ID with the HTTP client your app already uses.
api.postMessage(body = "hello", connectionId = bird.connectionId)在连接建立之前,该 ID 为 null,并且在重新连接后会改变。发起请求时,在浏览器中读取 bird.connection.connectionId,在 Swift 和 Kotlin 中读取 bird.connectionId。
将该值传给 exclude_connection_id,并将其作为不可信的请求数据进行验证。此字段可以阻止向某个连接投递事件,但不能授予对事件的访问权限。
被排除连接的行为
只有指定的连接会被排除。同一用户的其他标签页使用独立的连接,仍然会收到该事件。
排除一个未订阅或已不存在的连接 ID 不会产生错误。发布会正常投递给其他所有人。
何时不使用排除
排除适用于乐观更新的界面。如果客户端在应用变更之前等待事件到达,则不要排除它。否则,发起操作的标签页将保持过时状态。
后续步骤
- 发布事件介绍了发布载荷的其余部分,包括批量发送和广播。
- Presence 频道解释了为什么一个成员可以持有多个连接。
- 发布事件是该请求的完整参考。
相关资源
继续查阅此主题的文档、指南和示例。资源为英文。