【问题标题】:how to use nestjs redis microservice?如何使用nestjs redis 微服务?
【发布时间】:2019-06-14 22:06:01
【问题描述】:

我正在学习nestjs微服务,

我可以使用什么命令?

const pattern = { cmd: 'get' };
this.client.send<any>(pattern, data)

我怎样才能从redis接收数据?

constructor(private readonly appService: AppService) {}
      @Client({
        transport: Transport.REDIS,
        options: {
          url: 'redis://127.0.0.1:6379',
        },
      })
      client: ClientProxy;

      @Get()
      getHello(): any {
        const pattern = { cmd: 'get foo' };  //Please write sample code here in document
        const data = '';
        return this.client.send<any>(pattern, data);
      }

【问题讨论】:

    标签: node.js typescript redis microservices nestjs


    【解决方案1】:

    有两个方面需要分开。它们可以是一个nest.js 应用程序的一部分(例如hybrid application),也可以是几个不同的nest.js 应用程序:

    客户

    客户端广播有关主题/模式的消息,并从广播消息的接收者接收响应。

    首先,您必须连接您的客户端。您可以在onModuleInit 中执行此操作。在此示例中,ProductService 在创建新产品实体时广播一条消息。

    @Injectable()
    export class ProductService implements OnModuleInit {
    
      @Client({
        transport: Transport.REDIS,
        options: {
          url: 'redis://localhost:6379',
        },
      })
      private client: ClientRedis;
    
      async onModuleInit() {
        // Connect your client to the redis server on startup.
        await this.client.connect();
      }
    
      async createProduct() {
        const newProduct = await this.productRepository.createNewProduct();
        // Send data to all listening to product_created
        const response = await this.client.send({ type: 'product_created' }, newProduct).toPromise();
        return response;
      }
    }
    

    请记住,this.client.send 返回一个Observable。这意味着,在您对其进行subscribe 之前,什么都不会发生(您可以通过调用toPromise() 隐式执行此操作)。

    模式处理程序

    模式处理程序使用消息并将响应发送回客户端。

    @Controller()
    export class NewsletterController {
    
      @MessagePattern({ type: 'product_created' })
      informAboutNewProduct(newProduct: ProductEntity): string {
        await this.sendNewsletter(this.recipients, newProduct);
        return `Sent newsletter to ${this.recipients.length} customers`;
      }
    

    当然,参数处理程序也可以是客户端,因此可以接收和广播消息。

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2016-08-18
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 2020-07-15
      • 2022-06-11
      • 2020-02-04
      • 2023-02-06
      相关资源
      最近更新 更多