@acheetahk/redis
v2.6.0
Published
✨ work with redis
Downloads
105
Readme
Please use version greater than 2.5.0, the clustering and redlock will be supported at v3.0.0 😄 ✨
Methods Nav
about
redis
about
baseRedis methods
about
typescript decorator
about
javascript decorator function
Installation
npm install @acheetahk/redis
cnpm install @acheetahk/redis
yarn add @acheetahk/redis
Dependencies
{
"@types/ioredis": "4.17.7",
"ioredis": "^4.17.3"
}
Usage
redis
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
const redis = base.redis;
baseRedis - options
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [port] | number | string | Object | 6379 | Port of the Redis server, or a URL string(see the examples below), or the options
object(see the third argument). |
| [host] | string | Object | "localhost" | Host of the Redis server, when the first argument is a URL string, this argument is an object represents the options. |
| [options] | Object | | Other options. |
| [options.port] | number | 6379 | Port of the Redis server. |
| [options.host] | string | "localhost" | Host of the Redis server. |
| [options.family] | string | 4 | Version of IP stack. Defaults to 4. |
| [options.path] | string | null | Local domain socket path. If set the port
, host
and family
will be ignored. |
| [options.keepAlive] | number | 0 | TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive. |
| [options.noDelay] | boolean | true | Whether to disable the Nagle's Algorithm. By default we disable it to reduce the latency. |
| [options.connectionName] | string | null | Connection name. |
| [options.db] | number | 0 | Database index to use. |
| [options.password] | string | null | If set, client will send AUTH command with the value of this option when connected. |
| [options.dropBufferSupport] | boolean | false | Drop the buffer support for better performance. This option is recommended to be enabled when handling large array response and you don't need the buffer support. |
| [options.enableReadyCheck] | boolean | true | When a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server not respond to any commands. To work around this, when this option is true
, ioredis will check the status of the Redis server, and when the Redis server is able to process commands, a ready
event will be emitted. |
| [options.enableOfflineQueue] | boolean | true | By default, if there is no active connection to the Redis server, commands are added to a queue and are executed once the connection is "ready" (when enableReadyCheck
is true
, "ready" means the Redis server has loaded the database from disk, otherwise means the connection to the Redis server has been established). If this option is false, when execute the command when the connection isn't ready, an error will be returned. |
| [options.connectTimeout] | number | 10000 | The milliseconds before a timeout occurs during the initial connection to the Redis server. |
| [options.autoResubscribe] | boolean | true | After reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels. |
| [options.autoResendUnfulfilledCommands] | boolean | true | If true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected. |
| [options.lazyConnect] | boolean | false | By default, When a new Redis
instance is created, it will connect to Redis server automatically. If you want to keep the instance disconnected until a command is called, you can pass the lazyConnect
option to the constructor: javascript var redis = new Redis({ lazyConnect: true }); // No attempting to connect to the Redis server here. // Now let's connect to the Redis server redis.get('foo', function () { });
|
| [options.tls] | Object | | TLS connection support. See https://github.com/luin/ioredis#tls-options |
| [options.keyPrefix] | string | "''" | The prefix to prepend to all keys in a command. |
| [options.retryStrategy] | function | | See "Quick Start" section |
| [options.maxRetriesPerRequest] | number | | See "Quick Start" section |
| [options.reconnectOnError] | function | | See "Quick Start" section |
| [options.readOnly] | boolean | false | Enable READONLY mode for the connection. Only available for cluster mode. |
| [options.stringNumbers] | boolean | false | Force numbers to be always returned as JavaScript strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). |
| [options.enableAutoPipelining] | boolean | false | When enabled, all commands issued during an event loop iteration are automatically wrapped in a pipeline and sent to the server at the same time. This can improve performance by 30-50%. |
| [options.autoPipeliningIgnoredCommands] | string[] | [] | The list of commands which must not be automatically wrapped in pipelines. |
| [options.maxScriptsCachingTime] | number | 60000 | Default script definition caching time. |
onLock
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
const [test, result] = await Promise.all([
base.onLock('onLockTest', 5),
base.onLock('onLockTest'),
]);
// result = false
onLock - args
| Param | Type | Description | | --- | --- | --- | |key | string| string mutex lock key | |ttl | number| mutex lock expiration time, units are seconds |
freedLock
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
const result1 = await base.onLock('onLockTest', 1000); // true
const result2 = await base.onLock('onLockTest'); // false
await base1.freedLock('onLockTest');
const result3 = await base1.onLock('onLockTest'); // true
freedLock - args
| Param | Type | Description | | --- | --- | --- | |key | string| string mutex lock key |
lock
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
class Demo {
@base.lock('key', 5, true)
async doSomeThings(args: any) {
const result = await `<YOUR PROMISE FUNCTION>`(args);
return result;
}
}
const demo = new Demo();
// success
try {
const result = await demo.doSomeThings({ key: 'value'});
} catch (error) {
// console.log(error);
}
// error
try {
await Promise.all([
demo.doSomeThings({ key: 'value'}),
demo.doSomeThings({ key: 'value'})
]);
} catch (error) {
// Error: Frequent operation'
}
lock - args
| Param | Type | Description |
| --- | --- | --- |
|key | string| string mutex lock key |
|ttl | number| mutex lock expiration time, units are seconds |
|isAuto | boolean| whether to automatically serialization args
according to the bound function parameters, the default
is false
|
|message | string| failure information, the default
is Frequent operation
|
cache
import { BaseRedis } from '@acheetahk/redis';
let count = 0;
const base = new BaseRedis(`<YOUR OPTIONS>`);
class Demo {
@base.cache('cacheKey', 3600, true) // 1h
doSomeThings(num: number) {
return num + count;
}
}
const demo = new Demo();
const result = await demo.doSomeThings(1); // 1
const result1 = await demo.doSomeThings(2); // 1
await base.redis.del('cacheKey');
const result2 = await demo.doSomeThings(2); // 2
cache - args
| Param | Type | Description |
| --- | --- | --- |
|key | string| string cache key |
|ttl | number| expiration time, units are seconds |
|isAuto | boolean| whether to automatically serialization args
according to the bound function parameters, the default
is false
|
hashCache
import { BaseRedis } from '@acheetahk/redis';
let count = 0;
const base = new BaseRedis(`<YOUR OPTIONS>`);
class Demo {
@base.hashCache('hkey') // 1h
doSomeThings(num: number) {
return num + count;
}
}
const demo = new Demo();
const result = await demo.doSomeThings(1); // 1
const result1 = await demo.doSomeThings(2); // 1
await base.redis.hdel('hkey', autoMd5([1]));
const result2 = await demo.doSomeThings(2); // 2
hashCache - args
| Param | Type | Description | | --- | --- | --- | |hkey | string| hash cache key |
toLock
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
const getResult = async () => { return await doSomeThings() };
try {
await Promise.all([
toLock(base, 'toLock', getResult, 5).withArgs(),
toLock(base, 'toLock', getResult, 5).withArgs(),
]);
} catch (error) {
// Error: Frequent operation
}
toLock - args
| Param | Type | Description |
| --- | --- | --- |
|baseRedis | BaseRedis| instance by BaseRedis|
|key | string| string mutex lock key |
|next | Function| function to be executed |
|ttl | number| mutex lock expiration time, units are seconds |
|message | string| failure information, the default
is Frequent operation
|
getCache
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
let info = 'before ';
const getResult = async (num: string, num2: string) => {
const result = await doSomeThings();
const value = info + result + num + num2;
return value;
};
const result1 = await getCache(base, 'getCache', getResult, 10000).withArgs(123, 234); // 'before success123234';
info = 'now ';
const result2 = await getCache(base, 'getCache', getResult, 10000).withArgs(123, 234); // 'before success123234';
await base.redis.del('getCache');
const result3 = await getCache(base, 'getCache', getResult, 10000).withArgs(123, 234); // 'now success123234';
getCache - args
| Param | Type | Description | | --- | --- | --- | |baseRedis | BaseRedis| instance by BaseRedis| |key | string| string mutex lock key | |next | Function| function to be executed | |ttl | number| expiration time, units are seconds |
getHashCache
import { BaseRedis } from '@acheetahk/redis';
const base = new BaseRedis(`<YOUR OPTIONS>`);
let info = 'before ';
const getResult = async (num: string, num2: string) => {
const result = await doSomeThings();
const value = info + result + num + num2;
return value;
};
const result1 = await getHashCache(base, 'getHashCache', 'key', getResult).withArgs(123, 234); // 'before success123234'
info = 'now ';
const result2 = await getHashCache(base, 'getHashCache', 'key', getResult).withArgs(123, 234); // 'before success123234'
await base.redis.hdel('getHashCache', 'key');
const result4 = await getHashCache(base, 'getHashCache', 'key', getResult).withArgs(123, 234); // 'now success123234'
await base.redis.del('getHashCache');
getHashCache - args
| Param | Type | Description | | --- | --- | --- | |baseRedis | BaseRedis| instance by BaseRedis| |hkey | string| hash cache key | |key | string| hash table key | |next | Function| function to be executed |