|
1 | 1 | # cache-bridge |
2 | 2 |
|
3 | | -Makes managing data between cache and DB easier |
| 3 | +Simplify managing data between cache and database. |
4 | 4 |
|
5 | | -## **This package is still testing** |
| 5 | +## Features |
6 | 6 |
|
7 | | -so be careful if you want to use it in production. |
| 7 | +- Get data from cache, and automatically copy it from database when cache miss. |
| 8 | +- Will acquire the lock before accessing database, avoid [Cache stampede](https://en.wikipedia.org/wiki/Cache_stampede). |
| 9 | +- Supports [lru-cache](https://www.npmjs.com/package/lru-cache). |
| 10 | +- Supports Redis, via [node-redis](https://www.npmjs.com/package/redis) or [ioredis](https://www.npmjs.com/package/ioredis). |
8 | 11 |
|
9 | | -## Features |
| 12 | +## Example |
| 13 | + |
| 14 | +```typescript |
| 15 | +import { createClient } from 'redis' |
| 16 | +import { MongoClient, ObjectId } from 'mongodb' |
| 17 | +import { createBridge, RedisCacheClient } from './src' |
| 18 | + |
| 19 | +const redis = createClient() |
| 20 | +const mongo = new MongoClient('mongodb://localhost:27017') |
| 21 | + |
| 22 | +async function main (): Promise<void> { |
| 23 | + await redis.connect() |
| 24 | + await mongo.connect() |
| 25 | + |
| 26 | + const { bridge } = createBridge({ |
| 27 | + cacheClient: new RedisCacheClient({ client: redis }), |
| 28 | + prefix: 'cache', |
| 29 | + ttl: 5000, |
| 30 | + // set how to get data from the DB |
| 31 | + get: async (id) => { |
| 32 | + return await mongo.db().collection('a').findOne({ _id: new ObjectId(id) }) |
| 33 | + }, |
| 34 | + // set how to get multiple data from the DB |
| 35 | + getMany: async (idList) => { |
| 36 | + const list = await mongo.db().collection('a') |
| 37 | + .find({ |
| 38 | + _id: { $in: idList.map((id) => new ObjectId(id)) } |
| 39 | + }) |
| 40 | + .toArray() |
| 41 | + return new Map( |
| 42 | + list.map((data) => [data._id.toHexString(), data]) |
| 43 | + ) |
| 44 | + } |
| 45 | + }) |
| 46 | + |
| 47 | + const consoleData = async (id: string): Promise<void> => { |
| 48 | + console.log(await bridge.get(id)) |
| 49 | + } |
| 50 | + |
| 51 | + // when called sequentially |
| 52 | + const id1 = '000000000000000000000001' |
| 53 | + await consoleData(id1) // get data from the DB |
| 54 | + await consoleData(id1) // get data from the cache |
| 55 | + await consoleData(id1) // get data from the cache |
| 56 | + |
| 57 | + // when called simultaneously |
| 58 | + const id2 = '000000000000000000000002' |
| 59 | + await Promise.all([ |
| 60 | + consoleData(id2), // get data from the DB |
| 61 | + consoleData(id2), // wait for the previous line to store the data in the cache and get data from the cache |
| 62 | + consoleData(id2) // wait for and get data from the cache |
| 63 | + ]) |
| 64 | +} |
10 | 65 |
|
11 | | -- fill cache from DB when cache miss, including locking to avoid cache stampede |
| 66 | +main() |
| 67 | +``` |
0 commit comments