我学习nestjs微服务,
我可以使用什么命令?
const pattern = { cmd: 'get' };
this.client.send<any>(pattern, data)
而如何从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);
}
有两个方面需要分开。 它们可以是一个nest.js应用(例如部分混合应用 )或者是在几个不同的nest.js应用:
客户
客户端广播上的主题/图案的消息和接收从广播的消息的接收器(多个)的响应。
首先,你必须连接您的客户端。 你可以做,在onModuleInit
。 在这个例子中, 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;
}
}
请记住,这this.client.send
返回一个Observable
。 这意味着,什么都不会发生,直到你subscribe
它(你可以做隐式调用toPromise()
模式处理器
图案的处理程序使用消息,并发送回一个响应给客户机。
@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`;
}
当然,设置了一个param处理器也可以是一个客户端和与之接收和广播消息。