从 stackoverflow 找到一个答案."https://stackoverflow.com/questions/55942795/call-my-nestjs-microservice-with-nodejs-app" (https://link.segmentfault.com/?enc=JTF6I%2B%2BG5CGb73o%2BPx4yhg%3D%3D.D9hR6%2FppgAruZInVSRjBvE38XFjh3UmpFrdiX38rNzkMQI4F%2FhGLfUZYuThwqD9ISmExZCkEwZN3qgipAq3bwkR46v2PQs6566ayaLfyVkNCuVXdvFbzuaZb9Ep8qYzz)
import { ClientTCP } from "@nestjs/microservices";
import { lastValueFrom } from "rxjs";
async function bootstrap() {
const client = new ClientTCP({
host: "localhost",
port: 3001,
});
await client.connect();
const pattern = { cmd: "math:wordcount" };
const data = "12314";
const result = await lastValueFrom(client.send("math:wordcount", data)).catch(
(e) => {
console.log(`e`, e);
}
);
console.log(result);
}
bootstrap();
当然安装的话需要安装这些包,不然会缺少依赖...:
"@nestjs/common": "^10.3.0",
"@nestjs/core": "^10.3.0",
"@nestjs/microservices": "^10.3.0"