BroadcastChannel
在 Deno Deploy 中,程式碼會在世界各地的不同資料中心執行,以透過在最靠近客戶的資料中心提供服務來降低延遲。在瀏覽器中,BroadcastChannel
API 允許具有相同來源的不同分頁交換訊息。在 Deno Deploy 中,BroadcastChannel API 提供了各種執行個體之間的通訊機制;一個連接全球各地不同 Deploy 執行個體的簡單訊息匯流排。
建構函式
BroadcastChannel()
建構函式會建立新的 BroadcastChannel
實例,並連線到(或建立)提供的頻道。
let channel = new BroadcastChannel(channelName);
參數
名稱 | 類型 | 說明 |
---|---|---|
頻道名稱 | 字串 | 底層廣播頻道連線的名稱。 |
建構函式的傳回類型是 BroadcastChannel
實例。
屬性
名稱 | 類型 | 說明 |
---|---|---|
名稱 | 字串 | 底層廣播頻道的名稱。 |
onmessage | 函式 (或 null ) | 當頻道收到新訊息時執行的函式(MessageEvent )。 |
onmessageerror | 函式 (或 null ) | 當收到的訊息無法反序列化為 JavaScript 資料結構時執行的函式。 |
方法
名稱 | 說明 |
---|---|
close() | 關閉與底層頻道的連線。關閉後,您無法再將訊息傳送到頻道。 |
postMessage(message) | 將訊息傳送到底層頻道。訊息可以是字串、物件文字、數字或任何類型的 Object 。 |
BroadcastChannel
延伸 EventTarget
,讓您可以在 BroadcastChannel
實例上使用 EventTarget
的方法,例如 addEventListener
和 removeEventListener
。
範例:跨實例更新記憶體快取
像 BroadcastChannel
啟用的訊息匯流排的一個使用案例,是在網路不同資料中心執行的隔離區之間更新資料的記憶體內快取。在以下範例中,我們展示如何設定一個簡單的伺服器,使用 BroadcastChannel
來同步伺服器所有執行中的執行個體的狀態。
import { Hono } from "https://deno.land/x/hono/mod.ts";
// in-memory cache of messages
const messages = [];
// A BroadcastChannel used by all isolates
const channel = new BroadcastChannel("all_messages");
// When a new message comes in from other instances, add it
channel.onmessage = (event: MessageEvent) => {
messages.push(event.data);
};
// Create a server to add and retrieve messages
const app = new Hono();
// Add a message to the list
app.get("/send", (c) => {
// New messages can be added by including a "message" query param
const message = c.req.query("message");
if (message) {
messages.push(message);
channel.postMessage(message);
}
return c.redirect("/");
});
// Get a list of messages
app.get("/", (c) => {
// Return the current list of messages
return c.json(messages);
});
Deno.serve(app.fetch);
你可以使用 這個遊樂場 在 Deno Deploy 上自己測試這個範例。