@acheetahk/redis 中文文档教程

发布于 4年前 浏览 17 项目主页 更新于 3年前

#

@acheetahk/redis

@acheetahk/redis . supports all redis(singleton)methods and includes the best Cache and mutex decorators.


codecovbuild npm

请使用大于 2.5.0 的版本,集群和 redlock 将在 v3 支持。 0.0 ✨

Methods Nav

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

ParamTypeDefaultDescription
[port]number | string | Object6379Port of the Redis server, or a URL string(see the examples below), or the options object(see the third argument).
[host]string | Object&quot;localhost&quot;Host of the Redis server, when the first argument is a URL string, this argument is an object represents the options.
[options]ObjectOther options.
[options.port]number6379Port of the Redis server.
[options.host]string&quot;localhost&quot;Host of the Redis server.
[options.family]string4Version of IP stack. Defaults to 4.
[options.path]stringnullLocal domain socket path. If set the port, host and family will be ignored.
[options.keepAlive]number0TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive.
[options.noDelay]booleantrueWhether to disable the Nagle's Algorithm. By default we disable it to reduce the latency.
[options.connectionName]stringnullConnection name.
[options.db]number0Database index to use.
[options.password]stringnullIf set, client will send AUTH command with the value of this option when connected.
[options.dropBufferSupport]booleanfalseDrop 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]booleantrueWhen 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]booleantrueBy 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]number10000The milliseconds before a timeout occurs during the initial connection to the Redis server.
[options.autoResubscribe]booleantrueAfter reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels.
[options.autoResendUnfulfilledCommands]booleantrueIf true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected.
[options.lazyConnect]booleanfalseBy 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]ObjectTLS connection support. See https://github.com/luin/ioredis#tls-options
[options.keyPrefix]string&quot;&#x27;&#x27;&quot;The prefix to prepend to all keys in a command.
[options.retryStrategy]functionSee "Quick Start" section
[options.maxRetriesPerRequest]numberSee "Quick Start" section
[options.reconnectOnError]functionSee "Quick Start" section
[options.readOnly]booleanfalseEnable READONLY mode for the connection. Only available for cluster mode.
[options.stringNumbers]booleanfalseForce 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]booleanfalseWhen 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]number60000Default 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

ParamTypeDescription
keystringstring mutex lock key
ttlnumbermutex 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

ParamTypeDescription
keystringstring 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

ParamTypeDescription
keystringstring mutex lock key
ttlnumbermutex lock expiration time, units are seconds
isAutobooleanwhether to automatically serialization args according to the bound function parameters, the default is false
messagestringfailure 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

ParamTypeDescription
keystringstring cache key
ttlnumberexpiration time, units are seconds
isAutobooleanwhether 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

ParamTypeDescription
hkeystringhash 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
keystringstring mutex lock key
nextFunctionfunction to be executed
ttlnumbermutex lock expiration time, units are seconds
messagestringfailure 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
keystringstring mutex lock key
nextFunctionfunction to be executed
ttlnumberexpiration 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
hkeystringhash cache key
keystringhash table key
nextFunctionfunction to be executed


#

@acheetahk/redis

@acheetahk/redis ???? . supports all redis(singleton)methods and includes the best Cache and mutex decorators.


codecovbuild npm

Please use version greater than 2.5.0, the clustering and redlock will be supported at v3.0.0 ???? ✨

Methods Nav

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

ParamTypeDefaultDescription
[port]number | string | Object6379Port of the Redis server, or a URL string(see the examples below), or the options object(see the third argument).
[host]string | Object&quot;localhost&quot;Host of the Redis server, when the first argument is a URL string, this argument is an object represents the options.
[options]ObjectOther options.
[options.port]number6379Port of the Redis server.
[options.host]string&quot;localhost&quot;Host of the Redis server.
[options.family]string4Version of IP stack. Defaults to 4.
[options.path]stringnullLocal domain socket path. If set the port, host and family will be ignored.
[options.keepAlive]number0TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive.
[options.noDelay]booleantrueWhether to disable the Nagle's Algorithm. By default we disable it to reduce the latency.
[options.connectionName]stringnullConnection name.
[options.db]number0Database index to use.
[options.password]stringnullIf set, client will send AUTH command with the value of this option when connected.
[options.dropBufferSupport]booleanfalseDrop 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]booleantrueWhen 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]booleantrueBy 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]number10000The milliseconds before a timeout occurs during the initial connection to the Redis server.
[options.autoResubscribe]booleantrueAfter reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels.
[options.autoResendUnfulfilledCommands]booleantrueIf true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected.
[options.lazyConnect]booleanfalseBy 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]ObjectTLS connection support. See https://github.com/luin/ioredis#tls-options
[options.keyPrefix]string&quot;&#x27;&#x27;&quot;The prefix to prepend to all keys in a command.
[options.retryStrategy]functionSee "Quick Start" section
[options.maxRetriesPerRequest]numberSee "Quick Start" section
[options.reconnectOnError]functionSee "Quick Start" section
[options.readOnly]booleanfalseEnable READONLY mode for the connection. Only available for cluster mode.
[options.stringNumbers]booleanfalseForce 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]booleanfalseWhen 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]number60000Default 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

ParamTypeDescription
keystringstring mutex lock key
ttlnumbermutex 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

ParamTypeDescription
keystringstring 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

ParamTypeDescription
keystringstring mutex lock key
ttlnumbermutex lock expiration time, units are seconds
isAutobooleanwhether to automatically serialization args according to the bound function parameters, the default is false
messagestringfailure 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

ParamTypeDescription
keystringstring cache key
ttlnumberexpiration time, units are seconds
isAutobooleanwhether 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

ParamTypeDescription
hkeystringhash 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
keystringstring mutex lock key
nextFunctionfunction to be executed
ttlnumbermutex lock expiration time, units are seconds
messagestringfailure 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
keystringstring mutex lock key
nextFunctionfunction to be executed
ttlnumberexpiration 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

ParamTypeDescription
baseRedisBaseRedisinstance by BaseRedis
hkeystringhash cache key
keystringhash table key
nextFunctionfunction to be executed


    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文