跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

路由

最后更新 查看 MarkdownAgent 设置

Agents 使用与任何启用了 Lifecycle 的 Durable Object 相同的路由方式。routeAgentRequest() 会将 /agents/:binding/:name 发送到名为 :name 的 Agent。有关 URL 格式、路由选项、身份验证和自定义路由,请参阅路由。本页介绍 Agent 类额外提供的功能。

路由请求

src/index.jsjs
import { Agent, getAgentByName, routeAgentRequest } from "agents";

export class Counter extends Agent {
	initialState = { count: 0 };

	async increment() {
		this.setState({ count: this.state.count + 1 });
		return this.state.count;
	}
}

export default {
	async fetch(request, env) {
		if (new URL(request.url).pathname === "/api/increment") {
			const counter = await getAgentByName(env.Counter, "global");
			return Response.json({ count: await counter.increment() });
		}

		return (
			(await routeAgentRequest(request, env)) ??
			new Response("Not found", { status: 404 })
		);
	},
};
src/index.tsts
import { Agent, getAgentByName, routeAgentRequest } from "agents";

export class Counter extends Agent<Env, { count: number }> {
	initialState = { count: 0 };

	async increment(): Promise<number> {
		this.setState({ count: this.state.count + 1 });
		return this.state.count;
	}
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		if (new URL(request.url).pathname === "/api/increment") {
			const counter = await getAgentByName(env.Counter, "global");
			return Response.json({ count: await counter.increment() });
		}

		return (
			(await routeAgentRequest(request, env)) ??
			new Response("Not found", { status: 404 })
		);
	},
} satisfies ExportedHandler<Env>;

发往 /agents/counter/global 的请求会到达名为 global 的 Counter Agent。客户端也以相同方式连接:useAgent({ agent: "Counter", name: "global" })。

从 Worker 调用 Agent

getAgentByName(namespace, name, options?) 会返回用于 RPC 调用的 stub。与 getByName() 不同,它会在返回前启动 Agent,因此其功能模块和 onStart() 都已就绪。该方法接受 locationHint、jurisdiction、props 和 routingRetry。

属性(Props)

当请求或调用启动 Agent 时,Props 会将值传递给 onStart(props):

import { Agent, getAgentByName } from "agents";

export class Profile extends Agent {
	#userId;

	onStart(props) {
		this.#userId = props?.userId;
	}
}

export async function openProfile(env, userId) {
	return getAgentByName(env.Profile, userId, { props: { userId } });
}
import { Agent, getAgentByName } from "agents";

type Props = { userId: string };

export class Profile extends Agent<Env> {
	#userId: string | undefined;

	onStart(props?: Props) {
		this.#userId = props?.userId;
	}
}

export async function openProfile(env: Env, userId: string) {
	return getAgentByName(env.Profile, userId, { props: { userId } });
}

Props 只会传递给正在启动的 Agent。routeAgentRequest() 接受相同的 props 选项,并会将其传递给 URL 匹配到的 Agent。若要传递特定 Agent 的值,请使用 getAgentByName()。

子 Agent URL

buildAgentPath() 会构建 Agent 及其子 Agent的路径,每一层都包含一个 /sub/ 片段。在 Agent 内部,this.selfPath 保存其自身路径:

import { buildAgentPath } from "agents";

const path = buildAgentPath(
	[
		{ className: "Inbox", name: "alice" },
		{ className: "Chat", name: "chat-1" },
	],
	{ leafPath: "/callbacks/job" },
);
// /agents/inbox/alice/sub/chat/chat-1/callbacks/job
import { buildAgentPath } from "agents";

const path = buildAgentPath(
	[
		{ className: "Inbox", name: "alice" },
		{ className: "Chat", name: "chat-1" },
	],
	{ leafPath: "/callbacks/job" },
);
// /agents/inbox/alice/sub/chat/chat-1/callbacks/job

Agent 选项

静态选项 默认值 说明
sendIdentityOnConnect true 设置为 false,可让 Agent 的名称不出现在身份帧中
hibernate true 设置为 false,可在客户端连接期间让 Agent 保持在内存中
import { Agent } from "agents";

class SecureAgent extends Agent {
	static options = { sendIdentityOnConnect: false };
}

后续步骤

路由

URL 格式、路由选项、身份验证和自定义路由。

客户端 SDK

使用 useAgent 与 AgentClient 从浏览器连接。

这篇文档对您有帮助吗?