how to use nestjs redis microservice?
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.