如果我在端口80上有一个mongo:server.com/mongo
。我无法打开任何端口。我怎么能用Java连接它呢?
这不起作用:
mongodb://user:pass@server.com/mongo:80/dbName
30秒后的例外:
在server.com / dbName上连接时出错:30000后超时 等待匹配的服务器时的ms ReadPreferenceServerSelector {readPreference =初级}。客户端视图 集群状态是{type = UNKNOWN, servers = [{address = server.com / mongo:80,type = UNKNOWN, state = CONNECTING,exception = {com.mongodb.MongoSocketException: server.com/mongo},由{java.net.UnknownHostException引起: server.com/mongo}}]
我也尝试过:
mongodb://user:pass@server.com:80/mongo/dbName
例外是:
在server.com / dbName上连接期间出错:连接字符串 包含无效的主机' server.com:80 / mongo'。港口 ' 80 /蒙戈'不是有效的,它必须是0到0之间的整数 65535
我的java代码:
String url = "mongodb://user:pass@server.com/mongo:80/dbName";
MongoClientURI mongoUri = new MongoClientURI(uri);
MongoClient mongo = new MongoClient(mongoUri);
MongoDatabase db = mongo.getDatabase(dbName);
MongoIterable<String> collectionNames = db.listCollectionNames();
for (String name : collectionNames) {
System.out.println(name);
}
我的apache2站点配置:
<VirtualHost *:80>
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
LogLevel warn
<Location /mongo>
ProxyPass http://localhost:27017/
ProxyPassReverse http://localhost:27017/
</Location>
<Location /mongo/>
ProxyPass http://localhost:27017/
ProxyPassReverse http://localhost:27017/
</Location>
ExpiresActive On
ExpiresDefault "access plus 5184000 seconds"
AllowEncodedSlashes On
</VirtualHost>
卷曲正在回复(curl server.com/mongo
,curl server.com:80/mongo
)
看起来您正尝试通过HTTP访问本机上的MongoDB 司机口。
我的认证在mongo中是可以的:
>db.auth("user", "pass")
1
>use dbName
switched to db dbName
修改
使用mongo CLI没有任何响应:
mongo server.com
mongo server.com:80
mongo server.com:80/mongo
mongo server.com/mongo
mongo server.com/mongo:80
同样:
mongo user:pass@server.com/...
和
mongo -u user -p pass server.com/...
请注意:此处mongo
不是我的数据库名称,而是服务器上的额外路径
答案 0 :(得分:0)
主要问题是mongo将路径部分(/mongo
)理解为被调用数据库而不是以下路径部分(/dbName
)。
使用NGinx的解决方案是编辑可用网站,如下所示:
upstream stream_mongo_backend {
server localhost:27017;
}
server {
listen 80;
listen 443 ssl;
server_name server.com;
include path/to/cert.conf;
location /mongo {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://stream_mongo_backend/;
proxy_redirect off;
}
}