2014-05-18 89 views
1

我寫了一個樣例MongoDB數據庫輪詢器,它連續每3秒鐘輪詢一次數據庫。每3秒鐘輪詢一次MongoDB

在查詢數據庫時,我可以每次使用相同的遊標作爲查詢,還是每次都應該獲取新遊標並相應地關閉它?

import java.net.UnknownHostException; 
import java.sql.Connection; 
import java.util.ArrayList; 

import com.mongodb.BasicDBObject; 
import com.mongodb.DB; 
import com.mongodb.DBCollection; 
import com.mongodb.DBCursor; 
import com.mongodb.Mongo; 
import com.mongodb.MongoURI; 

    public class Data extends Thread { 
     static DB db = getConnection(""); 
     DBCollection table = db.getCollection("stock"); 
     DBCursor cursor = null; 

     public void run() { 
      while (true) { 
       try { 
        ArrayList<stocks> list = new ArrayList<stocks>(); 
        BasicDBObject searchQuery = new BasicDBObject(); 
        table.setObjectClass(stocks.class); 
        cursor = table.find(searchQuery); 
        while (cursor.hasNext()) { 
         stocks s = (stocks) cursor.next(); 
         list.add(s); 
        } 
        cursor.close(); 
        storeOrUpdate(list); 
        System.out.println("*****************"); 
        Thread.sleep(3000); 

       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     public static void main(String[] args) { 

      Data d = new Data(); 
      d.start(); 

     } 

    public static DB getConnection(String databaseName) { 
     if (db == null) { 
      System.out.println("==========================================="); 
      String textUri = "mongodb://krn1231:[email protected]:43388/stocks"; 
      MongoURI uri = new MongoURI(textUri); 
      Mongo m = null; 
      try { 
       m = new Mongo(uri); 
      } catch (UnknownHostException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      db = m.getDB("stocks"); 
      return db; 
     } else { 
      return db; 
     } 
    } 

    public void storeOrUpdate(ArrayList<stocks> list) throws Exception { 
     Connection connection = null; 
     connection = ConexionTest.getConnection(); 

     for (int i = 0; i < list.size(); i++) { 
      stocks stoc = list.get(i); 
      System.out.println(stoc.get("symbol")); 

     } 

    } 

} 

回答

1

Mongodb通常保持光標約20分鐘。因此,保留或忽略打開的光標並不是一個好主意,因爲這會影響您的表現。完成這項工作的理想方法是在完成工作後關閉光標。 (如果不使用,數據庫會在20分鐘後自動關閉光標。) 所以我建議關閉光標並每次打開一個新光標。