<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!
原文:http://blog.csdn.net/u010278923/article/details/42394231