如何使用nestjs redis microservice?

问题描述 投票:0回答:1

我正在学习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个回答
4
投票

您需要分开两个方面。它们可以是一个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`;
  }

当然,param处理程序也可以是客户端,并且由此接收和广播消息。

© www.soinside.com 2019 - 2024. All rights reserved.