2013-06-19 138 views
5

我正在尋找檢查MongoDB連接的最佳方法。 情況:客戶端向服務器發出請求(api)。並且服務器返回所有數據庫的狀態。MongoDB:檢查與數據庫的連接

什麼是最好的辦法呢?

回答

2

如果我正確理解你的問題,你想通過Web服務調用返回的狀態。你可以寫一個函數調用db.serverStatus()並讓它返回數據。點擊這裏,查看文檔:

Monitoring for MongoDB

5

我用這個:

Builder o = MongoClientOptions.builder().connectTimeout(3000); 
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3001), o.build());  

try { 
    mongo.getAddress(); 
} catch (Exception e) { 
    System.out.println("Mongo is down"); 
    mongo.close(); 
    return; 
} 
5

在Java MongoDriver 3.3.0使用ServerMonitorListener以確定服務器是否已啓動並連接與否。 下面是示例代碼,

public class ServerConnection implements ServerMonitorListener { 
    private MongoClient client; 

    public ServerConnection(){ 
     try { 
      MongoClientOptions clientOptions = new MongoClientOptions.Builder() 
       .addServerMonitorListener(this) 
       .build(); 

      client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions); 
     } catch (Exception ex) { 

     } 
    } 

    @Override 
    public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) { 
     // Ping Started 
    } 

    @Override 
    public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) { 
     // Ping Succeed, Connected to server 
    } 

    @Override 
    public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) { 
     // Ping failed, server down or connection lost 
    } 
} 
+0

好的,尋找我可以在新的mongodb java異步驅動程序中聲明這樣一個監聽器的地方......找不到。 MongoClientOptions似乎被MongoClientSettings取代,它沒有addServerMonitorListener() – Antonin

2

ping命令是用於測試服務器是否響應命令無操作。此命令將立即返回,即使服務器爲寫鎖定:

 try{ 

      DBObject ping = new BasicDBObject("ping", "1"); 
      mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping); 
     } catch (Exception exp){ 
      // MongoDb is down.. 
     }