Redis

Redis transporter implements the publish/subscribe messaging paradigm and leverages Pub/Sub feature of Redis. Published messages are categorized in channels, without knowing what subscribers (if any) will eventually receive the message. Each microservice can subscribe to any number of channels. In addition, more than one channel can be subscribed to at a time. Messages exchanged through channels are fire-and-forget, which means that if a message is published and there are no subscribers interested in it, the message is removed and cannot be recovered. Thus, you don’t have a guarantee that either messages or events will be handled by at least one service. A single message can be subscribed to (and received) by multiple subscribers.

Redis - 图1

Installation

To start building Redis-based microservices, first install the required package:

  1. $ npm i --save redis

Overview

To use the Redis transporter, pass the following options object to the createMicroservice() method:

  1. @@filename(main)
  2. const app = await NestFactory.createMicroservice(ApplicationModule, {
  3. transport: Transport.REDIS,
  4. options: {
  5. url: 'redis://localhost:6379',
  6. },
  7. });

info Hint The Transport enum is imported from the @nestjs/microservices package.

Likewise, to create a client instance, we need to pass an options object with the same properties we saw above in the createMicroservice() method.

  1. ClientsModule.register([
  2. {
  3. name: 'MATH_SERVICE',
  4. transport: Transport.REDIS,
  5. options: {
  6. url: 'redis://localhost:6379',
  7. }
  8. },
  9. ]),

Other options to create a client (either ClientProxyFactory or @Client()) can be used as well. You can read about them here.

Context

In more sophisticated scenarios, you may want to access more information about the incoming request. In Redis, you can access the RedisContext object.

  1. @@filename()
  2. @MessagePattern('notifications')
  3. getDate(@Payload() data: number[], @Ctx() context: RedisContext) {
  4. console.log(`Channel: ${context.getChannel()}`);
  5. }
  6. @@switch
  7. @Bind(Payload(), Ctx())
  8. @MessagePattern('notifications')
  9. getDate(data, context) {
  10. console.log(`Channel: ${context.getChannel()}`);
  11. }

info Hint @Payload(), @Ctx() and RedisContext are imported from @nestjs/microservices.

Options

The options object is specific to the chosen transporter. The REDIS transporter exposes the properties described below.

url Connection url
retryAttempts Number of times to retry message
retryDelay Delay between message retry attempts (ms)