将套接字客户端与NestJs微服务一起使用

编程入门 行业动态 更新时间:2024-10-26 17:26:04
本文介绍了将套接字客户端与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微服务一起使用

本文发布于:2023-11-23 11:15:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   NestJs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!