NestJs与Redis开发实战之监听Redis消息

351 阅读1分钟

redis 库选择

nestjs-redis: 年久失修,社区也不活跃。start数量(300+)

ioredis:官方推荐,社区活跃。start数量(12K+)

使用


// redis-cluster-listener.service.ts

import { Injectable, OnModuleInit } from '@nestjs/common';
import Redis from 'ioredis';
import { EventsGateway } from '../events/events.gateway'; //这是我的socket 文件
import { AppDto } from '../app/app.dto';

@Injectable()
export class RedisClusterListenerService implements OnModuleInit {
  private readonly redis;
  constructor(private readonly eventsGateway: EventsGateway) {
    this.redis = new Redis.Cluster([
      'redis://用户名:密码@地址:端口',
      'redis://:password@192.22.11.96:6001',
      'redis://:password@192.44.33.96:6002',
      // 添加更多 Redis 节点... 如果没有用户名那就不用填写
    ]);

    // 订阅 Redis 频道 某一个topIc
    this.redis.subscribe('GUIDE_REDIS_CHANNEL_TOPIC');
  }

  async onModuleInit() {
    // 监听消息
    this.redis.on('message', (channel: string, message: string) => {
      if (message) {
        this.eventsGateway.sendMessage(JSON.parse(message) as AppDto);
      }
      // 在这里处理消息
    });
  }
}

注入使用

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GatewayModule } from '../events/gateway.module'; // 我的socket
import { RedisClusterListenerService } from '../redis/redis-cluster-listener.service';

@Module({
  imports: [GatewayModule],
  controllers: [AppController],
  providers: [AppService, RedisClusterListenerService],
})
export class AppModule {}