node.js - 仅在本地主机上出现奇怪的 MongoDB 连接问题
问题描述
我有 3 台服务器运行 MongoDB 副本集,1 台主服务器,1 台辅助服务器,1 台仲裁器。而且我在连接到这个副本集时遇到问题。使用在 localhost 和备用服务器上运行的 test.js 文件进行测试。
- 从本地主机连接,节点 6.5.0:好的
- 从本地主机连接,节点 10.15.1:失败
- 从备用服务器连接,节点 6.5.0:OK
- 从备用服务器连接,节点 10.15.1:OK
这是我的 test.js 文件:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://root:password"+
"@mgdb1.mydomain,mgdb2.mydomain/vApp?replicaSet=rs0&authSource=admin";
console.log("Connecting...");
MongoClient.connect(url,(err,client)=>{
if (err!=null){
console.log("Error:",err);
return;
}
console.log("Connected.");
process.exit();
});
奇怪的是它显示 ECONNREFUSED 错误,但不是在副本集中 3 台服务器的 IP,它是我的 ISP 范围内的 IP。那么为什么它在连接后失败?它显示 TCPConnectWrap.afterConnect,是否意味着已经建立连接?
错误是这样的:
Connecting...
(node:1412) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Error: { Error: connect ECONNREFUSED 125.235.4.59:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '125.235.4.59',
port: 27017 }
编辑:
我目前的解决方法是直接连接到主服务器而不使用replicaset=rs0,但是,这不是所需的方式。
解决方案
我发现了问题。在云上的一组机器上创建副本集时,服务器的地址是服务器名称,只有同一服务器 LAN 上的其他机器知道。在办公室的本地主机上,没有这样的服务器名称。
解决方法1:
- 仅连接到主服务器或辅助服务器
解决方法2:
- 编辑 /etc/hosts 文件(或 c:\windows\system32\drivers\etc\hosts)
- 将服务器的名称指向其适当的 IP
推荐阅读
- reactjs - 无法在 Redux + Firebase 中获取用户描述
- qt - 在 QTableView 中显示具有“按下”状态的按钮
- node.js - 使用 N-API 从 Node.JS 调用 C(++) 函数
- html - 我怎样才能消除这个类似 Facebook 的加载程序中的闪烁?
- spring-boot - 谷歌云负载均衡器
- object-storage - MinioClient 线程安全
- algorithm - 在线性时间内找到第四小的元素
- python - Python什么时候释放内存?
- javascript - 将 React 添加到网站时,如何在多个文件中使用组件?
- swift - SwiftUI 列表行没有调整以适应内容