A ioredis module for Nest framework (node.js) using ioredis library
npm install --save @nestjs-modules/ioredis ioredis
yarn add @nestjs-modules/ioredis ioredis
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/ioredis';
import { AppController } from './app.controller';
@Module({
imports: [
RedisModule.forRoot({
type: 'single',
url: 'redis://localhost:6379',
}),
],
controllers: [AppController],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/ioredis';
import { AppController } from './app.controller';
@Module({
imports: [
RedisModule.forRoot({
type: 'cluster',
nodes: [
{
host: '127.0.0.1',
port: 6379
},
{
host: '127.0.0.2',
port: 6379
}
],
options: {
redisOptions: {
password: '123456'
}
}
}),
],
controllers: [AppController],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/ioredis';
import { AppController } from './app.controller';
@Module({
imports: [
RedisModule.forRootAsync({
useFactory: () => ({
type: 'single',
url: 'redis://localhost:6379',
}),
}),
],
controllers: [AppController],
})
export class AppModule {}
import { Module } from '@nestjs/common';
import { RedisModule } from '@nestjs-modules/ioredis';
import { AppController } from './app.controller';
@Module({
imports: [
RedisModule.forRootAsync({
useFactory: () => ({
type: 'cluster',
nodes: [
{
host: '127.0.0.1',
port: 6379
},
{
host: '127.0.0.2',
port: 6379
}
],
options: {
redisOptions: {
password: '123456'
}
}
}),
}),
],
controllers: [AppController],
})
export class AppModule {}
import Redis from 'ioredis';
import { Controller, Get } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
@Controller()
export class AppController {
constructor(
@InjectRedis() private readonly redis: Redis,
) {}
@Get()
async getHello() {
await this.redis.set('key', 'Redis data!');
const redisData = await this.redis.get("key");
return { redisData };
}
}
//health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { RedisHealthModule, } from '@nestjs-modules/ioredis';
@Module({
imports: [TerminusModule, RedisHealthModule],
controllers: [HealthController]
})
export class HealthModule {}
//health.controller.ts
import { Controller, Get } from '@nestjs/common';
import {
HealthCheckService,
HealthCheck,
HealthCheckResult
} from '@nestjs/terminus';
import { RedisHealthIndicator } from './redis.health';
@Controller('health')
export class HealthController {
constructor(
private health: HealthCheckService,
private redis: RedisHealthIndicator,
) {}
@Get()
@HealthCheck()
check(): Promise<HealthCheckResult> {
return this.health.check([
async () => this.redis.isHealthy('redis'),
]);
}
}
MIT