[英]how to use nestjs redis microservice?
I am learning nestjs microservice,我正在学习nestjs微服务,
What command can I use?我可以使用什么命令?
const pattern = { cmd: 'get' };
this.client.send<any>(pattern, data)
And how can I receive data from redis?以及如何从 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);
}
There are two sides you need to separate.有两个方面需要分开。 They can be part of one nest.js application (eg hybrid application ) or be in several different nest.js applications:它们可以是一个 nest.js 应用程序(例如混合应用程序)的一部分,也可以位于多个不同的 nest.js 应用程序中:
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
.你可以在onModuleInit
做到这onModuleInit
。 In this example, ProductService
broadcasts a message when a new product entity is created.在此示例中, 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;
}
}
Keep in mind, that this.client.send
returns an Observable
.请记住, this.client.send
返回一个Observable
。 This means, nothing will happen until you subscribe
to it (which you can implicitly do by calling toPromise()
).这意味着,在您subscribe
它之前什么都不会发生(您可以通过调用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.当然,参数处理程序也可以是客户端,从而接收和广播消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.