BroadcastChannel
在 Deno Deploy 中,代码在全球不同的数据中心运行,以便通过在离客户端最近的数据中心提供请求来减少延迟。在浏览器中,BroadcastChannel
API 允许相同来源的不同选项卡交换消息。在 Deno Deploy 中,BroadcastChannel API 提供了各种实例之间的通信机制;一个连接全球各种 Deploy 实例的简单消息总线。
Constructor Jump to heading
BroadcastChannel()
构造函数创建一个新的 BroadcastChannel
实例,并连接到(或创建)提供的通道。
let channel = new BroadcastChannel(channelName);
Parameters Jump to heading
name | type | description |
---|---|---|
channelName | string |
底层广播通道连接的名称。 |
构造函数的返回类型是 BroadcastChannel
实例。
Properties Jump to heading
name | type | description |
---|---|---|
name |
string |
底层广播通道的名称。 |
onmessage |
function (或 null ) |
当通道收到新消息 (MessageEvent ) 时执行的函数。 |
onmessageerror |
function (或 null ) |
当到达的消息无法反序列化为 JavaScript 数据结构时执行的函数。 |
Methods Jump to heading
name | description |
---|---|
close() |
关闭与底层通道的连接。关闭后,您将无法再向通道发布消息。 |
postMessage(message) |
向底层通道发布消息。消息可以是字符串、对象字面量、数字或任何类型的 Object 。 |
BroadcastChannel
扩展了 EventTarget
,这允许您在 BroadcastChannel
的实例上使用 EventTarget
的方法,如 addEventListener
和 removeEventListener
。
示例:跨实例更新内存缓存 Jump to heading
消息总线(如 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);
您可以使用此 playground 在 Deno Deploy 上自行测试此示例。