每隔3秒轮询一次MongoDB

时间:2014-05-18 05:59:24

标签: java mongodb

我编写了一个示例MongoDB数据库轮询器,它每3秒轮询一次数据库。

在查询数据库时,我是否可以每次使用相同的光标作为查询,还是每次都要获取新光标并相应地关闭它?

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:saibabagod1@ds043388.mongolab.com: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 个答案:

答案 0 :(得分:1)

Mongodb通常会将光标打开约20分钟。因此,保持或忽略打开游标不是一个好主意,因为这会影响您的性能。完成这项工作的理想方法是在完成工作后关闭光标。 (如果不使用,数据库将在20分钟后自动关闭光标。) 所以我建议每次关闭光标并打开一个新光标。