此示例展示 Durable Objects 是有状态的,意味着内存状态可以在请求之间保留。在短暂不活动后,Durable Object 将被驱逐,所有内存状态将丢失。下一个请求将重建对象,但不会显示上一个请求的城市,而是显示对象已重新初始化的消息。如果您需要应用状态在驱逐后存活,请使用 Storage API 将状态写入存储,或将数据存储在其他地方。
import { DurableObject } from "cloudflare:workers";
// Worker
export default {
async fetch(request, env) {
return await handleRequest(request, env);
},
};
async function handleRequest(request, env) {
let stub = env.LOCATION.getByName("A");
// Forward the request to the remote Durable Object.
let resp = await stub.fetch(request);
// Return the response to the client.
return new Response(await resp.text());
}
// Durable Object
export class Location extends DurableObject {
constructor(state, env) {
super(state, env);
// Upon construction, you do not have a location to provide.
// This value will be updated as people access the Durable Object.
// When the Durable Object is evicted from memory, this will be reset.
this.location = null;
}
// Handle HTTP requests from clients.
async fetch(request) {
let response = null;
if (this.location == null) {
response = new String(`
This is the first request, you called the constructor, so this.location was null.
You will set this.location to be your city: (${request.cf.city}). Try reloading the page.`);
} else {
response = new String(`
The Durable Object was already loaded and running because it recently handled a request.
Previous Location: ${this.location}
New Location: ${request.cf.city}`);
}
// You set the new location to be the new city.
this.location = request.cf.city;
console.log(response);
return new Response(response);
}
}from workers import DurableObject, Response, WorkerEntrypoint
# Worker
class Default(WorkerEntrypoint):
async def fetch(self, request):
return await handle_request(request, self.env)
async def handle_request(request, env):
stub = env.LOCATION.getByName("A")
# Forward the request to the remote Durable Object.
resp = await stub.fetch(request)
# Return the response to the client.
return Response(await resp.text())
# Durable Object
class Location(DurableObject):
def __init__(self, ctx, env):
super().__init__(ctx, env)
# Upon construction, you do not have a location to provide.
# This value will be updated as people access the Durable Object.
# When the Durable Object is evicted from memory, this will be reset.
self.location = None
# Handle HTTP requests from clients.
async def fetch(self, request):
response = None
if self.location is None:
response = f"""
This is the first request, you called the constructor, so this.location was null.
You will set this.location to be your city: ({request.js_object.cf.city}). Try reloading the page."""
else:
response = f"""
The Durable Object was already loaded and running because it recently handled a request.
Previous Location: {self.location}
New Location: {request.js_object.cf.city}"""
# You set the new location to be the new city.
self.location = request.js_object.cf.city
print(response)
return Response(response)最后,配置 Wrangler 文件以包含基于先前选择的 namespace 和类名称的 Durable Object 绑定 和 迁移。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "durable-object-in-memory-state",
"main": "src/index.ts",
"durable_objects": {
"bindings": [
{
"name": "LOCATION",
"class_name": "Location"
}
]
},
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": [
"Location"
]
}
]
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "durable-object-in-memory-state"
main = "src/index.ts"
[[durable_objects.bindings]]
name = "LOCATION"
class_name = "Location"
[[migrations]]
tag = "v1"
new_sqlite_classes = [ "Location" ]