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);
}
The Redis transporter implements the publish/subscribe messaging paradigm and leverages the 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.
Looking at the capabilities of an application, a microservice-based architecture has gained popularity in recent years. NestJS is a Node. JS framework based on ExpressJS, but it's more than that. In fact, NestJS gives you everything you need to create microservices easily.
In addition to traditional (sometimes called monolithic) application architectures, Nest natively supports the microservice architectural style of development.
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:
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()
).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With