
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 以進行分層快取:
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' ,
}),
});
await keyv.set( 'foo' , 'bar' );
const value = await keyv.get( 'foo' );
console.log(value);
|
登入後複製
使用命名空間
命名空間可防止鍵衝突並允許範圍清除:
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' );
|
登入後複製
緩存分層與可緩存
將 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(),
secondary: redisStore,
});
await cache.set( 'foo' , 'bar' , { ttl: 1000 });
const value = await cache.get( 'foo' );
console.log(value);
|
登入後複製
進階功能
批量操作
使用 setMany 和 getMany 提高效能:
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);
|
登入後複製
自訂配置
使用defaultTtl、keyPrefixSeparator 和clearBatchSize 等選項自訂您的設定。
以上是keyv-upstash 簡介:無伺服器 Redis 的無縫鍵值存儲的詳細內容。更多資訊請關注PHP中文網其他相關文章!