跳转到内容
搜索文档

读取键值对

最后更新 查看 MarkdownAgent 设置

要获取给定键的值,请在已绑定到 Worker 代码的任何 KV 命名空间KV 绑定(binding) 上调用 get() 方法:

// Read individual key
env.NAMESPACE.get(key);

// Read multiple keys
env.NAMESPACE.get(keys);
# Read individual key
self.env.NAMESPACE.get(key)

# Read multiple keys
self.env.NAMESPACE.get(keys)

get() 方法返回一个 promise,你可以 await 以获取值。

如果你以字符串形式请求单个键,promise 中将获得单个响应。如果未找到键,promise 将解析为字面量值 null

你也可以请求键数组。返回值将是找到的键值对的 Map, 未找到的键值为 null

export default {
	async fetch(request, env, ctx) {
		try {
			// Read single key, returns value or null
			const value = await env.NAMESPACE.get("first-key");

			// Read multiple keys, returns Map of values
			const values = await env.NAMESPACE.get(["first-key", "second-key"]);

			// Read single key with metadata, returns value or null
			const valueWithMetadata = await env.NAMESPACE.getWithMetadata("first-key");

			// Read multiple keys with metadata, returns Map of values
			const valuesWithMetadata = await env.NAMESPACE.getWithMetadata(["first-key", "second-key"]);

			return new Response({
				value: value,
				values: Object.fromEntries(values),
				valueWithMetadata: valueWithMetadata,
				valuesWithMetadata: Object.fromEntries(valuesWithMetadata)
			});
		} catch (e) {
			return new Response(e.message, { status: 500 });
		}
	},
};
from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        try:
            # Read single key, returns value or None
            value = await self.env.NAMESPACE.get("first-key")

            # Read multiple keys, returns dict of values
            values = await self.env.NAMESPACE.get(["first-key", "second-key"])

            # Read single key with metadata
            value_with_metadata = await self.env.NAMESPACE.getWithMetadata("first-key")

            # Read multiple keys with metadata
            values_with_metadata = await self.env.NAMESPACE.getWithMetadata(["first-key", "second-key"])

            return Response.json({
                "value": value,
                "values": values,
                "valueWithMetadata": value_with_metadata,
                "valuesWithMetadata": values_with_metadata,
            })
        except Exception as e:
            return Response(str(e), status=500)

参考

KV 提供以下方法用于读取:

get() 方法

使用 get() 方法获取单个值,或在给定多个键时获取多个值:

使用 get(key: string) 请求单个键

要获取单个键的值,请在已绑定到 Worker 代码的任何 KV 命名空间上调用 get() 方法:

env.NAMESPACE.get(key, type?);
// OR
env.NAMESPACE.get(key, options?);
self.env.NAMESPACE.get(key, type)
# OR
self.env.NAMESPACE.get(key, options)
参数
  • key: string
    • KV 对的键。
  • type: "text" | "json" | "arrayBuffer" | "stream"
    • 可选。要返回的值的类型。默认为 text
  • options: { cacheTtl?: number, type?: "text" | "json" | "arrayBuffer" | "stream" }
    • 可选。包含可选 cacheTtltype 属性的对象。cacheTtl 属性定义 KV 结果在访问的全球网络位置缓存的秒数(最小值:30)。type 属性定义要返回的值的类型。
响应
  • response: Promise<string | Object | ArrayBuffer | ReadableStream | null>
    • 请求的 KV 对的值。响应类型取决于为 get() 命令提供的 type 参数,如下所示:
    • textstring(默认)。
    • json:从 JSON 字符串解码的对象。
    • arrayBufferArrayBuffer 实例。
    • streamReadableStream

使用 get(keys: string[]) 请求多个键

要获取多个键的值,请在已绑定到 Worker 代码的任何 KV 命名空间上调用 get() 方法:

env.NAMESPACE.get(keys, type?);
// OR
env.NAMESPACE.get(keys, options?);
self.env.NAMESPACE.get(keys, type)
# OR
self.env.NAMESPACE.get(keys, options)
参数
  • keys: string[]
    • KV 对的键。最大:100 个键
  • type: "text" | "json"
    • 可选。要返回的值的类型。默认为 text
  • options: { cacheTtl?: number, type?: "text" | "json" }
    • 可选。包含可选 cacheTtltype 属性的对象。cacheTtl 属性定义 KV 结果在访问的全球网络位置缓存的秒数(最小值:30)。type 属性定义要返回的值的类型。
响应
  • response: Promise<Map<string, string | Object | null>>
    • 请求的 KV 对的值。如果未找到键,则该键返回 null。响应类型取决于为 get() 命令提供的 type 参数,如下所示:
      • textstring(默认)。
      • json:从 JSON 字符串解码的对象。

响应大小限制为 25 MB。超过此大小的响应将失败并显示 413 Error 错误消息。

getWithMetadata() 方法

使用 getWithMetadata() 方法获取单个值及其元数据,或获取多个值及其元数据:

使用 getWithMetadata(key: string) 请求单个键

要获取给定键的值及其元数据,请在已绑定到 Worker 代码的任何 KV 命名空间上调用 getWithMetadata() 方法:

env.NAMESPACE.getWithMetadata(key, type?);
// OR
env.NAMESPACE.getWithMetadata(key, options?);
self.env.NAMESPACE.getWithMetadata(key, type)
# OR
self.env.NAMESPACE.getWithMetadata(key, options)

元数据是可序列化的值,你将其附加到每个 KV 条目。

参数
  • key: string
    • KV 对的键。
  • type: "text" | "json" | "arrayBuffer" | "stream"
    • 可选。要返回的值的类型。默认为 text
  • options: { cacheTtl?: number, type?: "text" | "json" | "arrayBuffer" | "stream" }
    • 可选。包含可选 cacheTtltype 属性的对象。cacheTtl 属性定义 KV 结果在访问的全球网络位置缓存的秒数(最小值:30)。type 属性定义要返回的值的类型。
响应
  • response: Promise<{ value: string | Object | ArrayBuffer | ReadableStream | null, metadata: string | null }>

    • 包含请求的 KV 对的值和元数据的对象。value 属性的类型取决于为 getWithMetadata() 命令提供的 type 参数,如下所示:

如果请求的键值对没有关联元数据,元数据将返回 null

使用 getWithMetadata(keys: string[]) 请求多个键

要获取给定键集的值及其元数据,请在已绑定到 Worker 代码的任何 KV 命名空间上调用 getWithMetadata() 方法:

env.NAMESPACE.getWithMetadata(keys, type?);
// OR
env.NAMESPACE.getWithMetadata(keys, options?);
self.env.NAMESPACE.getWithMetadata(keys, type)
# OR
self.env.NAMESPACE.getWithMetadata(keys, options)
参数
  • keys: string[]
    • KV 对的键。最大:100 个键
  • type: "text" | "json"
    • 可选。要返回的值的类型。默认为 text
  • options: { cacheTtl?: number, type?: "text" | "json" }
    • 可选。包含可选 cacheTtltype 属性的对象。cacheTtl 属性定义 KV 结果在访问的全球网络位置缓存的秒数(最小值:30)。type 属性定义要返回的值的类型。
响应
  • response: Promise<Map<string, { value: string | Object | null, metadata: string | Object | null }>

    • 包含请求的 KV 对的值和元数据的对象。value 属性的类型取决于为 getWithMetadata() 命令提供的 type 参数,如下所示:
      • textstring(默认)。
      • json:从 JSON 字符串解码的对象。
    • 元数据的类型取决于存储的内容,可以是字符串或对象。

如果请求的键值对没有关联元数据,元数据将返回 null

响应大小限制为 25 MB。超过此大小的响应将失败并显示 413 Error 错误消息。

指南

type 参数

对于简单值,使用默认的 text 类型,以 string 形式提供值。为方便起见,还指定了 json 类型,它会在返回对象之前将 JSON 值转换为对象。对于大值,使用 stream 请求 ReadableStream。对于二进制值,使用 arrayBuffer 请求 ArrayBuffer

对于大值,type 的选择会对延迟和 CPU 使用率产生明显影响。作为参考,type 从最快到最慢的顺序为 streamarrayBuffertextjson

cacheTtl 参数

cacheTtl 是一个参数,定义 KV 结果在访问的全球网络位置缓存的秒数。

以秒为单位定义时间长度有助于减少相对不常读取的键的冷读取延迟。如果你的数据是一次写入或很少写入,cacheTtl 很有用。

如果你的数据经常更新且需要在写入后不久看到更新,不建议使用 cacheTtl,因为从其他全球网络位置进行的写入在缓存值过期之前不可见。

cacheTtl 参数必须是大于或等于 30 的整数。60 是默认值。cacheTtl 的最大值为 Number.MAX_SAFE_INTEGER

一旦在某个区域使用给定的 cacheTtl 读取了键,它将在该区域缓存直到 cacheTtl 结束或被驱逐。这会影响 KV 内置缓存层的区域层和中心层。写入 Workers KV 时,KV 内部的区域和中心缓存层中的区域将使用新写入的结果重新验证。

通过批量请求在每次 Worker 调用中请求更多键

Workers 每次调用限制为 1,000 次外部服务操作。这适用于 Workers KV,如 Workers KV 限制 中所述。

要在每次操作中读取超过 1,000 个键,你可以使用批量读取操作在单次操作中读取多个键。这些计为 1,000 操作限制中的一次操作。

通过合并键减少基数

如果你有一组具有混合使用模式(一些热键和一些冷键)的相关键值对,请考虑合并它们。通过将冷键与热键合并,冷键将与热键一起缓存,这比作为独立键未缓存时提供更快的读取。

合并为「超级」KV 条目

一种合并技术是将所有键和值作为超级键值对象的一部分。示例如下。

key1: value1
key2: value2
key3: value3

变为

coalesced: {
  key1: value1,
  key2: value2,
  key3: value3,
}

通过合并值,冷键受益于因热键的访问模式而保持在缓存中温热。

如果你不需要独立更新各个值,这效果最好,否则可能产生竞态条件。

  • 优势:不常访问的键保留在缓存中。
  • 劣势:结果值的大小可能使 worker 超出内存限制。安全更新值需要某种锁定机制

其他访问 KV 的方法

你可以使用 Wrangler 从命令行读取键值对,并从 REST API 读取

这篇文档对您有帮助吗?