Nestjs Redis
Redis component for NestJs with cluster support.
Installation
Yarn
yarn add nestjs-redis-cluster
NPM
npm install nestjs-redis-cluster --save
Getting Started
RedisModule
Let's register the ClusterModule and RedisModule in app.module.ts
import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis-cluster';
@Module({
imports: [RedisModule.register(options)],
})
export class AppModule {}
With Async
import { Module } from '@nestjs/common';
import { RedisModule } from 'nestjs-redis-redis';
@Module({
imports: [
RedisModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.get('redis'),
inject: [ConfigService],
}),
],
})
export class AppModule {}
Config looks like this for RedisModule with single client
export default {
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
db: parseInt(process.env.REDIS_DB),
password: process.env.REDIS_PASSWORD,
keyPrefix: process.env.REDIS_PRIFIX,
};
Or;
export default {
url: 'redis://:authpassword@127.0.0.1:6380/4',
};
With custom error handler
export default {
url: 'redis://:authpassword@127.0.0.1:6380/4',
onClientReady: client => {
client.on('error', err => {});
},
};
With multi client
export default [
{
name: 'test1',
url: 'redis://:authpassword@127.0.0.1:6380/4',
},
{
name: 'test2',
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
db: parseInt(process.env.REDIS_DB),
password: process.env.REDIS_PASSWORD,
keyPrefix: process.env.REDIS_PRIFIX,
},
];
And use in your service
import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis-cluster';
@Injectable()
export class TestService {
constructor(private readonly redisService: RedisService) {}
async root(): Promise<boolean> {
const client = await this.redisService.getClient('test');
return true;
}
}
Options
interface RedisOptions {
name?: string;
url?: string;
port?: number;
host?: string;
family?: number;
path?: string;
keepAlive?: number;
connectionName?: string;
password?: string;
db?: number;
enableReadyCheck?: boolean;
keyPrefix?: string;
retryStrategy?(times: number): number | false;
maxRetriesPerRequest?: number | null;
reconnectOnError?(error: Error): boolean | 1 | 2;
enableOfflineQueue?: boolean;
connectTimeout?: number;
autoResubscribe?: boolean;
autoResendUnfulfilledCommands?: boolean;
lazyConnect?: boolean;
tls?: tls.ConnectionOptions;
sentinels?: Array<{ host: string; port: number }>;
name?: string;
readOnly?: boolean;
dropBufferSupport?: boolean;
showFriendlyErrorStack?: boolean;
}
ClusterModule
Let's register the RedisClusterModule in app.module.ts
import { Module } from '@nestjs/common';
import { RedisClusterModule } from 'nestjs-redis-cluster';
@Module({
imports: [RedisClusterModule.register(options)],
})
export class AppModule {}
With Async
import { Module } from '@nestjs/common';
import { ClusterModule } from 'nestjs-redis-cluster';
@Module({
imports: [
RedisClusterModule.forRootAsync({
useFactory: (configService: ConfigService) =>
configService.get('cluster'),
inject: [ConfigService],
}),
],
})
export class AppModule {}
Config looks like this for RedisClusterModule
export default {
nodes: [
{
host: 6380,
port: '127.0.0.1',
},
{
host: 6381,
port: '127.0.0.1',
},
],
};
Or;
export default {
nodes: [
{
url: 'redis://:authpassword@127.0.0.1:6380/4',
},
{
url: 'redis://:authpassword@127.0.0.1:6381/4',
},
],
};
With custom error handler
export default {
nodes: [
{
url: 'redis://:authpassword@127.0.0.1:6380/4',
},
],
onClusterReady: cluster => {
cluster.on('error', err => {});
},
};
With multiple clusters
export default [
{
name: 'test1',
nodes: [
{
url: 'redis://:authpassword@127.0.0.1:6380/4',
url: 'redis://:authpassword@127.0.0.1:6380/5',
},
],
},
{
name: 'test2',
nodes: [
{
host: process.env.REDIS_HOST,
port: parseInt(process.env.REDIS_PORT),
db: parseInt(process.env.REDIS_DB),
password: process.env.REDIS_PASSWORD,
keyPrefix: process.env.REDIS_PRIFIX,
},
],
},
];
And use in your service
import { Injectable } from '@nestjs/common';
import { RedisClusterService } from 'nestjs-redis-cluster';
@Injectable()
export class TestService {
constructor(private readonly redisService: RedisClusterService) {}
async root(): Promise<boolean> {
const client = await this.redisService.getCluster('test');
return true;
}
}
Options
Almost all the options are passed to ioredis/cluster (https://github.com/luin/ioredis/blob/master/lib/cluster/ClusterOptions.ts)
The only additional options are name
, nodes
, and onClusterReady
.
interface RedisClusterOptions {
name?: string;
nodes: (string | number | { url: string?, host?: string, port?: number )[];
clusterRetryStrategy?: (
times: number,
reason?: Error
) => number | void | null;
enableOfflineQueue?: boolean;
enableReadyCheck?: boolean;
scaleReads?: NodeRole | Function;
maxRedirections?: number;
retryDelayOnFailover?: number;
retryDelayOnClusterDown?: number;
retryDelayOnTryAgain?: number;
slotsRefreshTimeout?: number;
slotsRefreshInterval?: number;
redisOptions?: any;
lazyConnect?: boolean;
dnsLookup?: DNSLookupFunction;
natMap?: INatMap;
}
That's it!