Other
The original author fixed the bug on GitHub, but NPM didn't fix it. In order to solve the problem of slow download module, he republished one for personal use only。
Original author: https://github.com/skunight/nestjs-redis
Nestjs Redis
Redis component for NestJs.
Installation
Yarn
yarn add nestjs-redis
NPM
npm install nestjs-redis --save
Getting Started
Let's register the RedisModule in app.module.ts
import { Module } from '@nestjs/common'
import { RedisModule} from 'nestjs-redis'
@Module({
imports: [
RedisModule.register(options)
],
})
export class AppModule {}
With Async
import { Module } from '@nestjs/common';
import { RedisModule} from 'nestjs-redis'
@Module({
imports: [
RedisModule.forRootAsync({
useFactory: (configService: ConfigService) => configService.get('redis'),
inject:[ConfigService]
}),
],
})
export class AppModule {}
And the config file look like this
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';
@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;
}
That's it!