All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.dceast.platform.task.db.DBUtil Maven / Gradle / Ivy

The newest version!
package cn.dceast.platform.task.db;

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

import cn.dceast.platform.task.config.TaskConfig;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * MongoDB util inited by spring ioc container,and destroyed by container close
 * invoking destroy method
 *
 * @author ruijf
 */
public class DBUtil {

    private static MongoClient mongoClient;

    private static DB db;

    private static String host;

    private static String dbName;

    private static String username;

    private static String password;

    public static void init() {
        try {

            host = TaskConfig.mongodb_task_host;
            dbName = TaskConfig.mongodb_task_dbName;
            username = TaskConfig.mongodb_task_userName;
            password = TaskConfig.mongodb_task_password;

            String[] hostArr = host.split("\\,");
            List serverList = new ArrayList();
            for (String h : hostArr) {
                serverList.add(new ServerAddress(h));
            }

            List credentialsList = null;
            if (username != null && username.trim().length() > 0 &&
                    password != null && password.trim().length() > 0) {
                credentialsList = new ArrayList();
                credentialsList.add(MongoCredential.createCredential(username, dbName, password.toCharArray()));
            }

            MongoClientOptions options = MongoClientOptions.builder()
                    .minConnectionsPerHost(TaskConfig.mongodb_task_minConnectionsPerHost)//default=0
                    .connectionsPerHost(TaskConfig.mongodb_task_connectionsPerHost)//默认值100
                    .threadsAllowedToBlockForConnectionMultiplier(5)//default=5。最大可阻塞的线程数倍数。最大可阻塞的线程数 connectionsPerHost*threadsAllowedToBlockForConnectionMultiplier
                    .maxWaitTime(TaskConfig.mongodb_task_maxWaitTime)//default=12000。线程最大等待一个可用链接时间
                    .maxConnectionIdleTime(TaskConfig.mongodb_task_maxConnectionIdleTime)//10分钟。
                    .maxConnectionLifeTime(0)//链接最大的生命周期。0不限制
                    .connectTimeout(TaskConfig.mongodb_task_connectTimeout)//链接超时时间。默认10秒
                    .socketTimeout(0)//socket timeout.default=0不限制
                    .socketKeepAlive(false)//default is false
                    .build();


            mongoClient = new MongoClient(serverList, credentialsList, options);
            db = mongoClient.getDB(dbName);
        } catch (Exception e) {
            throw new MongoDBInitException("Fail to init mongodb!");
        }
    }

    public static void destroy() {
        if (mongoClient != null) {
            /*
             * if (logger.isDebugEnabled()) {
             * logger.debug("closing the db collection...closed"); }
             */
            mongoClient.close();
        }
    }

    public static DBCollection getColl(String name) {
        return db.getCollection(name);
    }

    public static DBCollection createCollection(String name, BasicDBObject param) {
        return db.createCollection(name, param);
    }

    public static boolean CollectionExists(String name) {
        return db.collectionExists(name);
    }

    /**
     * 创建数据库。此方法操作超级管理员用户才可以使用
     *
     * @param dbName dbName
     */
    public static void createDatabase(String dbName) {
        DB database = mongoClient.getDB(dbName);

        boolean isExistColl = database.collectionExists("version");
        if (!isExistColl) {
            DBCollection c = database.getCollection("c1");

            BasicDBObject basicDBObject = new BasicDBObject();
            basicDBObject.append("f1", "v1");
            c.insert(basicDBObject);
            c.drop();
        }

    }

    /**
     * 新增用户。此方法操作超级管理员用户才可以使用
     * 1. 如果数据库不存在,则创建;存在,忽略创建数据库。
     * 2. 如果用户不存在,则创建;存在,忽略创建用户。
     * 3. 用户变更密码,直接调用此方法。
     *
     * @param dbName dbName
     * @param userName userName
     * @param password password
     */
    public static void createUser(String dbName, String userName, String password) {
        DB database = mongoClient.getDB(dbName);
        database.addUser(userName, password.toCharArray());

    }

    /**
     * 删除用户
     *
     * @param dbName dbName
     * @param userName  userName
     */
    public static void dropUser(String dbName, String userName) {
        DB database = mongoClient.getDB(dbName);
        database.removeUser(userName);
    }

    /**
     * 删除数据库
     *
     * @param dbName dbName
     */
    public static void dropDatabase(String dbName) {
        DB database = mongoClient.getDB(dbName);
        database.dropDatabase();
    }

    public static int nextValue(String counterName) {
        BasicDBObject query = new BasicDBObject("name", counterName);
        BasicDBObject fields = new BasicDBObject("value", true);
        BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("value", 1));
        BasicDBObject newObj = (BasicDBObject) db.getCollection("counter")
                .findAndModify(query, fields, null, false, update, true, true);
        return newObj.getInt("value");
    }

    public static void closeDBCursor(DBCursor dbCursor) {
        if (dbCursor != null) {
            dbCursor.close();
        }
    }


    public static void main(String[] args) {
        TaskConfig.init();
        DBUtil.init();

        //测试mongodb空闲链接释放
//		for(int i=0;i<100;i++){
//			new Thread(new Runnable() {
//				
//				@Override
//				public void run() {
//					DBUtil.getColl("app").findOne();
//					Thread.currentThread().interrupt();
//				}
//			}).start();
//		}
//		
//		try {
//			Thread.sleep(300000);
//			System.out.println("============");
//			Thread.sleep(300000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}


        DBUtil.destroy();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy