java连接mongodb报错

mongodb 专栏收录该内容
1 篇文章 0 订阅

<span style="background-color: rgb(255, 255, 255); font-family: Arial, Helvetica, sans-serif;">写一个简短的测试程序却报错,郁闷</span>

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="html">public static void main(String[] args) {    
    
  try {    
    
   Mongo mongo = new Mongo("10.2.167.27",27017);    
    
   DB db = mongo.getDB("company");    
    
   DBCollection collection = db.getCollection("employees");    
    
   BasicDBObject employee = new BasicDBObject();    
   employee.put("name", "Hannah");    
   employee.put("no", 2);    
    
   collection.insert(employee);    
    
   BasicDBObject searchEmployee = new BasicDBObject();    
   searchEmployee.put("no", 2);    
    
   DBCursor cursor = collection.find(searchEmployee);    
    
   while (cursor.hasNext()) {    
    System.out.println(cursor.next());    
   }    
    
   System.out.println("The Search Query has Executed!");    
    
  } catch (UnknownHostException e) {    
   e.printStackTrace();    
  } catch (MongoException e) {    
   e.printStackTrace();    
  }    
    
 }    

 


报错信息如下:


java.io.IOException: couldn't connect to [/10.2.167.27:27017] bc:java.net.ConnectException: Connection refused: connect
at com.mongodb.DBPort._open(DBPort.java:224)
at com.mongodb.DBPort.go(DBPort.java:101)
at com.mongodb.DBPort.go(DBPort.java:82)
at com.mongodb.DBPort.findOne(DBPort.java:142)
at com.mongodb.DBPort.runCommand(DBPort.java:151)
at com.mongodb.DBTCPConnector.fetchMaxBsonObjectSize(DBTCPConnector.java:429)
at com.mongodb.Mongo.getMaxBsonObjectSize(Mongo.java:544)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:244)
at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:217)
at com.mongodb.DBCollection.insert(DBCollection.java:87)
at mongodb.MongoDBClient.main(MongoDBClient.java:28)



看看服务器的端口:tcp        0      0 127.0.0.1:27017             0.0.0.0:*                   LISTEN      31933/mongod  


说明端口监听已ok。那就是配置问题

打开vim /etc/mongod.conf 

# Listen to local interface only. Comment out to listen on all interfaces. 
bind_ip=127.0.0.1


看到一条这样的记录。端口对谁开放。注释了。ok就可以远程访问了。

得到正确结果如下:

{ "_id" : { "$oid" : "54a8fcad2d1dc6f5db50564b"} , "name" : "Hannah" , "no" : 2}
The Search Query has Executed!

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值