将套接字客户端与NestJs微服务一起使用 [英] Use socket client with NestJs microservice

查看:511
本文介绍了将套接字客户端与NestJs微服务一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始与NestJs合作,并在尝试测试我的 NestJs微服务应用程序时得到了库存使用 TCP客户端

I started working with NestJs recently and got stock while trying to test my NestJs microservices app using a TCP client

是否可以使用非嵌套应用触发@EventPattern@MessagePattern()?

Is it possible to trigger an @EventPattern or @MessagePattern() using a non-nest app?

尝试此方法时,套接字客户端仅停留在trying to connect上.

When trying this method the the socket client just stuck on trying to connect.

有什么想法吗?

谢谢.

推荐答案

2020年2月更新

自Nest v6.6.0起,将外部服务与消息反序列化器集成变得更加容易.
看看相应的 PR .

您必须正确设置端口才能与nest一起使用:

You have to set up the ports correctly to use it with nest:

您要发送的图案是

<json-length>#{"pattern": <pattern-name>, "data": <your-data>[, "id": <message-id>]}

示例:

76#{"pattern":"sum","data":[0,3,3],"id":"ce51ebd3-32b1-4ae6-b7ef-e018126c4cc4"}

参数id用于@MessagePattern,如果没有该参数,将触发@EventPattern.

The parameter id is for @MessagePattern, without it @EventPattern will be triggered.

在您的main.ts中,您设置了嵌套服务器.那就是您要从Packet Sender发送到的端口(输入1).

In your main.ts you setup the nest server. That's the port you want to send to from Packet Sender (enter at 1).

const app = await NestFactory.createMicroservice(AppModule, {
  transport: Transport.TCP,
  options: { host: 'localhost', port: 3005 },
  //                            ^^^^^^^^^^
});

然后,您希望您的巢@Client收听来自Packet Sender的消息(请参见图片中的位置2)

Then you want your nest @Client to listen to messages coming from Packet Sender (see position 2 in image)

@Client({
  transport: Transport.TCP,
  options: { host: 'localhost', port: 52079 },
  //                            ^^^^^^^^^^^  
})
private client: ClientTCP;

然后连接您的客户端:

async onModuleInit() {
  await this.client.connect();
}

并定义一个@MessagePattern:

@MessagePattern('sum')
sum(data: number[]): number {
  console.log(data);
  return data.reduce((a, b) => a + b, 0);
}

如您所见,在示例中,我正在发送[0,3,3],并且nest正确地以总和6进行响应.

As you can see, in the example I'm sending [0,3,3] and nest correctly responds with the sum 6.

这篇关于将套接字客户端与NestJs微服务一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆