1. 程式人生 > >JAVA單例MongoDB工具類

JAVA單例MongoDB工具類

JAVA驅動版本:

        <!--java mongo -->
        <dependency>  
             <groupId>org.mongodb</groupId>  
	     <artifactId>mongo-java-driver</artifactId>  
             <version>3.2.0</version>   
	</dependency>

工具類程式碼:

package com.zmx.ssm.util;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;

public enum MongoUtil {
	
	/**
     * 定義一個列舉的元素,它代表此類的一個例項
     */
    instance;

    private MongoClient mongoClient;

    static { 

        // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
        // List<ServerAddress> listHost = Arrays.asList(new ServerAddress("localhost", 27017),new ServerAddress("localhost", 27018));
        // instance.mongoClient = new MongoClient(listHost);

        // 大部分使用者使用mongodb都在安全內網下,但如果將mongodb設為安全驗證模式,就需要在客戶端提供使用者名稱和密碼:
        // boolean auth = db.authenticate(myUserName, myPassword);       
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        // options.autoConnectRetry(true);// 自動重連true
        // options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
        builder.connectionsPerHost(300);// 連線池設定為300個連線,預設為100
        builder.connectTimeout(15000);// 連線超時,推薦>3000毫秒
        builder.maxWaitTime(5000); //
        builder.socketTimeout(0);// 套接字超時時間,0無限制
        builder.threadsAllowedToBlockForConnectionMultiplier(5000);// 執行緒佇列數,如果連線執行緒排滿了佇列就會丟擲“Out of semaphores to get db”錯誤。
        MongoClientOptions options = builder.build();
        
        instance.mongoClient =  new MongoClient(new ServerAddress("localhost", 27017), options);
    }

    // ------------------------------------共用方法---------------------------------------------------
    /**
     * 獲取DB例項 - 指定DB
     * 
     * @param dbName
     * @return
     */
    public MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }

    /**
     * 獲取collection物件 - 指定Collection
     * 
     * @param collName
     * @return
     */
    public MongoCollection<Document> getCollection(String dbName, String collName) {
        if (null == collName || "".equals(collName)) {
            return null;
        }
        if (null == dbName || "".equals(dbName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

    /**
     * 查詢DB下的所有表名
     */
    public List<String> getAllCollections(String dbName) {
        MongoIterable<String> colls = getDB(dbName).listCollectionNames();
        List<String> _list = new ArrayList<String>();
        for (String s : colls) {
            _list.add(s);
        }
        return _list;
    }

    /**
     * 獲取所有資料庫名稱列表
     * 
     * @return
     */
    public MongoIterable<String> getAllDBNames() {
        MongoIterable<String> s = mongoClient.listDatabaseNames();
        return s;
    }

    /**
     * 刪除一個數據庫
     */
    public void dropDB(String dbName) {
        getDB(dbName).drop();
    }

    /**
     * 查詢物件 - 根據主鍵_id
     * 
     * @param collection
     * @param id
     * @return
     */
    public Document findById(MongoCollection<Document> coll, String id) {
        ObjectId _idobj = null;
        try {
            _idobj = new ObjectId(id);
        } catch (Exception e) {
            return null;
        }
        Document myDoc = coll.find(Filters.eq("_id", _idobj)).first();
        return myDoc;
    }

    /** 統計數 */
    public int getCount(MongoCollection<Document> coll) {
        int count = (int) coll.count();
        return count;
    }

    /** 條件查詢 */
    public MongoCursor<Document> find(MongoCollection<Document> coll, Bson filter) {
        return coll.find(filter).iterator();
    }

    /** 分頁查詢 */
    public MongoCursor<Document> findByPage(MongoCollection<Document> coll, Bson filter, int pageNo, int pageSize) {
        Bson orderBy = new BasicDBObject("_id", 1);
        return coll.find(filter).sort(orderBy).skip((pageNo - 1) * pageSize).limit(pageSize).iterator();
    }

    /**
     * 通過ID刪除
     * 
     * @param coll
     * @param id
     * @return
     */
    public int deleteById(MongoCollection<Document> coll, String id) {
        int count = 0;
        ObjectId _id = null;
        try {
            _id = new ObjectId(id);
        } catch (Exception e) {
            return 0;
        }
        Bson filter = Filters.eq("_id", _id);
        DeleteResult deleteResult = coll.deleteOne(filter);
        count = (int) deleteResult.getDeletedCount();
        return count;
    }

    /**
     * @param coll
     * @param id
     * @param newdoc
     * @return
     */
    public Document updateById(MongoCollection<Document> coll, String id, Document newdoc) {
        ObjectId _idobj = null;
        try {
            _idobj = new ObjectId(id);
        } catch (Exception e) {
            return null;
        }
        Bson filter = Filters.eq("_id", _idobj);
        // coll.replaceOne(filter, newdoc); // 完全替代
        coll.updateOne(filter, new Document("$set", newdoc));
        return newdoc;
    }

    public void dropCollection(String dbName, String collName) {
        getDB(dbName).getCollection(collName).drop();
    }

    /**
     * 關閉Mongodb
     */
    public void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }

    /**
     * 測試入口
     * 
     * @param args
     */
    public static void main(String[] args) {

        String dbName = "GC_MAP_DISPLAY_DB";
        String collName = "COMMUNITY_BJ";
        MongoCollection<Document> coll = MongoUtil.instance.getCollection(dbName, collName);

        // 插入多條
        // for (int i = 1; i <= 4; i++) {
        // Document doc = new Document();
        // doc.put("name", "zhoulf");
        // doc.put("school", "NEFU" + i);
        // Document interests = new Document();
        // interests.put("game", "game" + i);
        // interests.put("ball", "ball" + i);
        // doc.put("interests", interests);
        // coll.insertOne(doc);
        // }

        // // 根據ID查詢
        // String id = "556925f34711371df0ddfd4b";
        // Document doc = MongoDBUtil2.instance.findById(coll, id);
        // System.out.println(doc);

        // 查詢多個
        // MongoCursor<Document> cursor1 = coll.find(Filters.eq("name", "zhoulf")).iterator();
        // while (cursor1.hasNext()) {
        // org.bson.Document _doc = (Document) cursor1.next();
        // System.out.println(_doc.toString());
        // }
        // cursor1.close();

        // 查詢多個
        // MongoCursor<Person> cursor2 = coll.find(Person.class).iterator();

        // 刪除資料庫
        // MongoDBUtil2.instance.dropDB("testdb");

        // 刪除表
        // MongoDBUtil2.instance.dropCollection(dbName, collName);

        // 修改資料
        // String id = "556949504711371c60601b5a";
        // Document newdoc = new Document();
        // newdoc.put("name", "時候");
        // MongoDBUtil.instance.updateById(coll, id, newdoc);

        // 統計表
        // System.out.println(MongoDBUtil.instance.getCount(coll));

        // 查詢所有
        Bson filter = Filters.eq("count", 0);
        MongoUtil.instance.find(coll, filter);

    }



}