how to use nestjs redis microservice?

2019-08-14 16:06发布

问题:

I am learning nestjs microservice,

What command can I use?

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

And how can I receive data from 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);
      }

回答1:

There are two sides you need to separate. They can be part of one nest.js application (e.g. hybrid application) or be in several different nest.js applications:

Client

The client broadcasts messages on a topic/pattern and receives a response from the receiver(s) of the broadcasted message.

First, you have to connect your client. You can do that in onModuleInit. In this example, ProductService broadcasts a message when a new product entity is created.

@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;
  }
}

Keep in mind, that this.client.send returns an Observable. This means, nothing will happen until you subscribe to it (which you can implicitly do by calling toPromise()).

Pattern Handler

The pattern handler consumes messages and sends a response back to the client.

@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`;
  }

Of course, a param handler could also be a client and therewith both receive and broadcast messages.