Making cache with Redis
$ npm i @tadashi/cache-redis
parameter | type | required | default | description |
---|---|---|---|---|
opts | Object | no | see below | Options for configuring the cache. |
parameter | type | required | default | description |
---|---|---|---|---|
address | String|String[] | no | 127.0.0.1:6379 | The address of the Redis server. |
namespace | String | no | app | A namespace for the cache keys. |
redisOptions | Object | no | - | See configuration options |
To use Cluster
, set addresses separated by commas or an array and set clusterOptions.
import Cache from '@tadashi/cache-redis'
const cache = new Cache({
address: '127.0.0.1:6379, 127.0.0.1:6380, 127.0.0.1:6381',
// or
address: ['127.0.0.1:6379', '127.0.0.1:6380', '127.0.0.1:6381'],
// and
redisOptions: {
clusterOptions: {
retryDelayOnClusterDown: 500,
// ...
}
}
})
import Cache from '@tadashi/cache-redis'
const _cache = new Cache({
redisOptions: {
keyPrefix: 'api'
},
namespace: 'example'
})
async function find(key) {
try {
const cache = await _cache.get(key)
if (cache) {
return cache
}
const result = await getDataFromSomeWhere(key)
await _cache.set(key, result, 'PX', 3600)
return result
} catch (err) {
throw err
}
}
await find('foo')
// => data from getDataFromSomeWhere
await find('foo')
// => data from cache
Important
Buy me a coffee!
BTC: bc1q7famhuj5f25n6qvlm3sssnymk2qpxrfwpyq7g4
MIT © Thiago Lagden