keyv-upstash 简介:无服务器 Redis 的无缝键值存储

来源:undefined 2025-02-03 02:34:51 1024

github:https://github.com/mahdavipanah/keyv-upstash

keyv-upstash 是 keyv 的存储适配器,可将其连接到无服务器 redis 平台 upstash redis。借助此适配器,您可以为无服务器应用程序中的键值存储提供简单、高效且灵活的解决方案。

什么是keyv?

keyv是一个多功能的键值存储库,通过适配器支持多个后端。它提供:

基于 ttl 的过期:非常适合缓存或持久存储。

命名空间支持:避免共享环境中的按键冲突。

可扩展性:轻松构建自定义模块或添加压缩等功能。

keyv 可与许多适配器配合使用,例如 redis、sqlite、mongodb,现在还支持 upstash redis 的 keyv-upstash。

为什么选择 keyv-upstash?

keyv-upstash 通过与 upstash redis 集成来扩展 keyv 的功能,提供:

无服务器兼容性:upstash redis 无需管理连接即可工作,自动扩展,非常适合无服务器应用程序。

灵活:兼容keyv生态,支持第三方扩展。

cache layering:与 cacheable 结合进行多层缓存。

无供应商锁定:与 serverless-redis-http 完全兼容,因此您可以设置自己的无服务器 redis 并使用此适配器。

入门

按照以下步骤集成 keyv-upstash:

1.安装keyv和keyv-upstash

安装 keyv 和 upstash 适配器:

1

npm install keyv keyv-upstash

登录后复制

可选:安装 cacheable 以进行分层缓存:

1

npm install cacheable

登录后复制

2. 设置 keyv-upstash

确保您在 upstash 中创建了 redis 数据库。以下是如何在项目中使用 keyv-upstash:

基本用法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import keyv from keyv;

import { keyvupstash } from keyv-upstash;

const keyv = new keyv({

store: new keyvupstash({

url: your-upstash-redis-url,

token: your-upstash-redis-token,

}),

});

// set a key-value pair

await keyv.set(foo, bar);

// retrieve the value

const value = await keyv.get(foo);

console.log(value); // bar

登录后复制
使用命名空间

命名空间可防止键冲突并允许范围清除:

1

2

3

4

5

6

7

8

9

const keyv = new keyv({

store: new keyvupstash({

url: your-upstash-redis-url,

token: your-upstash-redis-token,

namespace: my-namespace,

}),

});

await keyv.set(foo, bar); // stored as my-namespace::foo

登录后复制
缓存分层与可缓存

将 keyv-upstash 与 cacheable 结合起来进行多层缓存:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import { cacheable } from cacheable;

const redisstore = new keyvupstash({

url: your-upstash-redis-url,

token: your-upstash-redis-token,

});

const cache = new cacheable({

primary: new map(), // fast in-memory caching

secondary: redisstore, // persistent redis caching

});

await cache.set(foo, bar, { ttl: 1000 }); // stores in both layers

const value = await cache.get(foo); // fast lookup from memory or redis

console.log(value); // bar

登录后复制

高级功能

批量操作

1

2

3

4

5

6

7

await keyv.setMany([

{ key: key1, value: value1 },

{ key: key2, value: value2 },

]);

const values = await keyv.getMany([key1, key2]);

console.log(values); // [value1, value2]

登录后复制

自定义配置

使用defaultttl、keyprefixseparator 和clearbatchsize 等选项自定义您的设置。

以上就是keyv-upstash 简介:无服务器 Redis 的无缝键值存储的详细内容,更多请关注php中文网其它相关文章!

最新文章