com.weibo.datasys.common.db.DBManager.java Source code

Java tutorial

Introduction

Here is the source code for com.weibo.datasys.common.db.DBManager.java

Source

/**
 *  Copyright (c)  2016-2020 Weibo, Inc.
 *  All rights reserved.
 *
 *  This software is the confidential and proprietary information of Weibo, 
 *  Inc. ("Confidential Information"). You shall not
 *  disclose such Confidential Information and shall use it only in
 *  accordance with the terms of the license agreement you entered into with Weibo.
 */
package com.weibo.datasys.common.db;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.weibo.datasys.common.conf.ConfigFactory;
import com.weibo.datasys.common.data.CommonData;
import com.weibo.datasys.common.util.StringUtils;

/**
 * 
 *SQL???
 *
 **/
public class DBManager {

    private static Logger logger = LoggerFactory.getLogger(DBManager.class);

    /**
     * ???
     */
    private static Map<String, CommonData> defaultDSConfigMap = new ConcurrentHashMap<String, CommonData>();

    /**
     * ????
     */
    private static Map<String, CommonData> dynDSConfigMap = new ConcurrentHashMap<String, CommonData>();

    /**
     * ??
     */
    private static Map<String, BasicDataSource> dsMap;

    /**
     * ?DBManager?????
     */
    public synchronized static void init() {
        if (dsMap == null || dsMap.isEmpty()) {
            // ??
            logger.info("[InitDBManager] - Start.");
            dsMap = new HashMap<String, BasicDataSource>();
            // ?????
            getDefaultDSConfig();
            for (CommonData configData : defaultDSConfigMap.values()) {
                try {
                    initDataSource(configData);
                } catch (Exception e) {
                    logger.error("[InitDefaultDataSourceError] - ", e);
                }
            }
            for (CommonData configData : dynDSConfigMap.values()) {
                try {
                    initDataSource(configData);
                } catch (Exception e) {
                    logger.error("[InitDynamicDataSourceError] - ", e);
                }
            }
            logger.info("[InitDBManager] - Done.");
        } else {
            // ?
            logger.info("[InitDBManager] - Already initialized.");
        }
    }

    /**
     * 
     * ?????
     * 
     * @param dsname
     *            ??????
     */
    public static void initDataSource(String dsname) throws DBException {
        try {
            // ????
            CommonData configData = defaultDSConfigMap.get(dsname);
            if (null == configData) {
                // ?????
                configData = dynDSConfigMap.get(dsname);
            }
            initDataSource(configData);
        } catch (Exception e) {
            throw new DBException(e);
        }
    }

    /**
     * 
     * ?????
     * 
     * @param configData
     */
    private static void initDataSource(CommonData configData) {
        String dsname = configData.getBaseField("dsname");

        BasicDataSource dataSource = new BasicDataSource();
        // ??
        dataSource.setDriverClassName(configData.getBaseField("driverClassName"));
        // ??
        dataSource.setUrl(configData.getBaseField("connectURL"));
        // ???
        dataSource.setUsername(configData.getBaseField("username"));
        dataSource.setPassword(configData.getBaseField("password"));
        // ?
        dataSource.setInitialSize(StringUtils.parseInt(configData.getBaseField("initialSize"), 1));
        // ?
        dataSource.setMinIdle(StringUtils.parseInt(configData.getBaseField("minIdle"), 1));
        // 
        dataSource.setMaxIdle(StringUtils.parseInt(configData.getBaseField("maxIdle"), 1));
        // 
        dataSource.setMaxActive(StringUtils.parseInt(configData.getBaseField("maxActive"), 1));
        // ?,?(ms)
        dataSource.setMaxWait(StringUtils.parseInt(configData.getBaseField("maxWait"), 1000));

        // ??
        dataSource.setTestWhileIdle(true);
        // ?sql?
        dataSource.setValidationQuery("select 'test'");
        // ?
        dataSource.setValidationQueryTimeout(5000);
        // 
        dataSource.setTimeBetweenEvictionRunsMillis(3600000);
        // ??
        dataSource.setMinEvictableIdleTimeMillis(3600000);

        dsMap.put(dsname, dataSource);

        logger.info("[InitDataSourceOK] - dsname={}", dsname);
    }

    /**
     * 
     * ???????configData
     * 
     * @param configData
     *            ???(??)<br>
     *            dsname??????<br>
     *            driverClassName??<br>
     *            connectURL?url<br>
     *            db???<br>
     *            username??<br>
     *            password?<br>
     *            initialSize??1<br>
     *            minIdle?1<br>
     *            maxIdle1<br>
     *            maxActive1<br>
     *            maxWait?ms1000<br>
     * 
     * @throws DBException
     *             ????????
     */
    public static void addDataSource(CommonData configData) throws DBException {
        try {
            String dsname = configData.getBaseField("dsname");
            if (dsMap.get(dsname) != null) {
                throw new DBException("DataSource: " + dsname + " alread existed, please remove it first.");
            }
            dynDSConfigMap.put(dsname, configData);
            initDataSource(configData);
            logger.info("[AddDataSourceOK] - dsname={}", dsname);
        } catch (Exception e) {
            throw new DBException(e);
        }
    }

    /**
     * 
     * ?????????????
     * 
     * @param dsname
     */
    public static void removeDataSource(String dsname) {
        try {
            dynDSConfigMap.remove(dsname);
            BasicDataSource ds = dsMap.remove(dsname);
            if (ds != null) {
                ds.close();
                logger.info("[RemoveDataSourceOK] - dsname={}", dsname);
            }
        } catch (Exception e) {
            logger.error("[RemoveDataSourceError] - ", e);
        }
    }

    /**
     * 
     * ???????{@code DBManager.initDataSource(String)}
     * ?????
     * 
     * @param dsname
     */
    public static void closeDataSource(String dsname) {
        try {
            BasicDataSource ds = dsMap.get(dsname);
            if (ds != null) {
                ds.close();
                logger.info("[CloseDataSourceOK] - dsname={}", dsname);
            }
        } catch (Exception e) {
            logger.error("[CloseDataSourceError] - ", e);
        }
    }

    /**
     * ????{@code DBManager.init()}
     */
    public static void closeAllDataSource() {
        for (String dsname : dsMap.keySet()) {
            closeDataSource(dsname);
        }
        dsMap.clear();
        dsMap = null;
    }

    /**
     * ???????
     * 
     * @return
     * @throws DBException
     *             ?????
     */
    public static Connection getConnection(String dsname) throws DBException {
        Connection connection = null;
        BasicDataSource ds = dsMap.get(dsname);
        if (ds == null) {
            throw new DBException("NO DataSource for dsname: " + dsname);
        }
        try {
            connection = ds.getConnection();
            connection.setAutoCommit(true);
        } catch (Exception e) {
            logger.error("[GetConnError] - e.msg={} | ds={}.", e.getMessage(), dsname);
            throw new DBException(e);
        }
        return connection;
    }

    /**
     * 
     * ??
     * 
     * @param conn
     * @param ps
     */
    public static void releaseConnection(Connection conn, PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (Exception e) {
                logger.error("[ClosePSError] - ", e);
            }
        }
        if (conn != null) {
            try {
                if (!conn.isClosed())
                    conn.close();
            } catch (Exception e) {
                logger.error("[CloseConnectionError] - ", e);
            }
        }
    }

    /**
     * ?????
     */
    private static void getDefaultDSConfig() {
        String xpath = "dataSources.dataSource";
        int dsCount = ConfigFactory.getList(xpath + ".dsname").size();
        for (int i = 0; i < dsCount; i++) {
            String dsXpath = xpath + "(" + i + ")";
            // ?
            String driverClassName = ConfigFactory.getString(dsXpath + ".driverClassName", "com.mysql.jdbc.Driver");
            // ?
            int initialSize = ConfigFactory.getInt(dsXpath + ".initialSize", 1);
            // ?
            int minIdle = ConfigFactory.getInt(dsXpath + ".minIdle", 1);
            // 
            int maxIdle = ConfigFactory.getInt(dsXpath + ".maxIdle", 1);
            // 
            int maxActive = ConfigFactory.getInt(dsXpath + ".maxActive", 1);
            // ?,?(ms)
            int maxWait = ConfigFactory.getInt(dsXpath + ".maxWait", 1000);
            // ????
            String dsName = ConfigFactory.getString(dsXpath + ".dsname");
            // 
            String connectURL = ConfigFactory.getString(dsXpath + ".connectURL");
            // ???
            String db = ConfigFactory.getString(dsXpath + ".db");
            // ??
            String username = ConfigFactory.getString(dsXpath + ".username");
            // ?
            String password = ConfigFactory.getString(dsXpath + ".password");

            CommonData configData = new CommonData();
            configData.setBaseField("dsName", dsName);
            configData.setBaseField("connectURL", connectURL);
            configData.setBaseField("db", db);
            configData.setBaseField("username", username);
            configData.setBaseField("password", password);
            configData.setBaseField("driverClassName", driverClassName);
            configData.setBaseField("initialSize", initialSize);
            configData.setBaseField("minIdle", minIdle);
            configData.setBaseField("maxIdle", maxIdle);
            configData.setBaseField("maxActive", maxActive);
            configData.setBaseField("maxWait", maxWait);

            defaultDSConfigMap.put(dsName, configData);
        }
    }
}