首頁 > web前端 > js教程 > keyv-upstash 簡介:無伺服器 Redis 的無縫鍵值存儲

keyv-upstash 簡介:無伺服器 Redis 的無縫鍵值存儲

Barbara Streisand
發布: 2024-12-26 14:45:10
原創
518 人瀏覽過

Introducing keyv-upstash: Seamless Key-Value Storage for Serverless Redis

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 的功能,提供:

  1. 無伺服器相容性:Upstash Redis 無需管理連線即可運作,自動擴展,非常適合無伺服器應用程式。

  2. 靈活:相容於Keyv生態,支援第三方擴充。

  3. Cache Layering:與 Cacheable 結合進行多層快取。

  4. 無供應商鎖定:與 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'

登入後複製

進階功能

批量操作

使用 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); // ['value1', 'value2']

登入後複製

自訂配置

使用defaultTtl、keyPrefixSeparator 和clearBatchSize 等選項自訂您的設定。

以上是keyv-upstash 簡介:無伺服器 Redis 的無縫鍵值存儲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板