Java 数据库服务

package com.panda.core.db.impl;

import com.panda.core.log.log.util.Tools;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库服务
 * Created by Lovell on 16/6/18.
 */
public class DBService {
    private static Logger logger = LoggerFactory.getLogger(DBService.class);

    private static String DB_CONFIG_FILE = "/mysql.properties";
    private static String HK_CONFIG_FILE = "/hikari.properties";

    // 数据库服务器addr
    private String dbUrl = null;
    // 数据库连接端口
    private short dbPort = 0;
    // 数据库名称
    private String dbName = null;
    // 数据库登录用户名
    private String dbUsername = null;
    // 数据库登录密码
    private String dbPassword = null;

    private volatile long hkConnectionTimeout;
    private volatile long hkValidationTimeout;
    private volatile long hkIdleTimeout;

    // 数据库连接池最小闲置连接
    private volatile short hkMinIdle = 0;
    // 最大生命周期
    private volatile long hkMaxLifetime =  0;
    // 数据库连接池最大连接数
    private volatile short hkMaxPoolSize = 0;

    // 数据库连接池的名称
    private String hkPoolName = null;
    // 数据库预编译
    private boolean hkCachePrepStmts = false;
    // 数据库预编译缓冲池的大小
    private short hkPrepStmtCacheSize = 0;
    // 数据库预编译数据库查询语句的最大长度
    private short hkPrepStmtCacheSqlLimit = 0;
    // 数据预编译功能是否开启
    private boolean hkUseServerPrepStmts = false;
    // 是否自动提交
    private boolean hkIsAutoCommit = false;

    // 数据库缓冲池
    private HikariDataSource dataSource;

    private static DBService dBService;

    public static DBService getInstance() {
        if (dBService == null) {
            dBService = new DBService();
        }
        return dBService;
    }

    public void setConfigFilePathName(final String dbPath, final String hkPath) {
        setDBConfigFilePathName(dbPath);
        setHKConfigFilePathName(hkPath);
    }

    public void setDBConfigFilePathName(final String path) {
        if (path.charAt(0) == '/') {
            DB_CONFIG_FILE = path;
        } else {
            DB_CONFIG_FILE = "/" + path;
        }
    }

    public void setHKConfigFilePathName(final String path) {
        if (path.charAt(0) == '/') {
            HK_CONFIG_FILE = path;
        } else {
            HK_CONFIG_FILE = "/" + path;
        }
    }

    public void start() throws IOException, SQLException {
        Properties dbProp = new Properties();
        // 编译运行时获取项目根路径下build/classes/main路径;jar运行时获取.jar路径
        String strPath = Tools.getPath();
        File dbFile = new File(strPath + DB_CONFIG_FILE);
        // 获取Resource路径的配置文件
//        InputStream dbIn = DBService.class.getClass().getResourceAsStream(DB_CONFIG_FILE);
        InputStream dbIn = new FileInputStream(dbFile);
        dbProp.load(dbIn);

        Properties hkProp = new Properties();
        File hkFile = new File(strPath + HK_CONFIG_FILE);
        // 获取Resource路径的配置文件
//        InputStream hkIn = DBService.class.getClass().getResourceAsStream(HK_CONFIG_FILE);
        InputStream hkIn = new FileInputStream(hkFile);
        hkProp.load(hkIn);

        dbUrl = String.valueOf(dbProp.getProperty("mysql.url"));
        dbPort = Short.valueOf(dbProp.getProperty("mysql.port"));
        dbName = String.valueOf(dbProp.getProperty("mysql.name"));
        dbUsername = String.valueOf(dbProp.getProperty("mysql.username"));
        dbPassword = String.valueOf(dbProp.getProperty("mysql.password"));

        hkPoolName = String.valueOf(hkProp.getProperty("hikari.poolName"));
        hkMinIdle = Short.valueOf(hkProp.getProperty("hikari.minIdle"));
        hkMaxPoolSize = Short.valueOf(hkProp.getProperty("hikari.maxPoolSize"));
        hkCachePrepStmts = Boolean.valueOf(hkProp.getProperty("hikari.cachePrepStmts"));
        hkPrepStmtCacheSize = Short.valueOf(hkProp.getProperty("hikari.prepStmtCacheSize"));
        hkPrepStmtCacheSqlLimit = Short.valueOf(hkProp.getProperty("hikari.prepStmtCacheSqlLimit"));
        hkUseServerPrepStmts =  Boolean.valueOf(hkProp.getProperty("hikari.useServerPrepStmts"));
        hkIsAutoCommit = Boolean.valueOf(hkProp.getProperty("hikari.isAutoCommit"));
        hkMaxLifetime = Long.valueOf(hkProp.getProperty("hikari.maxLifetime"));
        if (dbUrl == null || dbUrl.length() == 0) {
            System.out.println("DB ip address error!");
            System.exit(0);
        }

        HikariConfig config = new HikariConfig();
        config.setPoolName(hkPoolName);
        config.setMinimumIdle(hkMinIdle);
        config.setMaximumPoolSize(hkMaxPoolSize);
        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");

        config.addDataSourceProperty("serverName", dbUrl);
        config.addDataSourceProperty("port", dbPort);
        config.addDataSourceProperty("databaseName", dbName);
        config.addDataSourceProperty("user", dbUsername);
        config.addDataSourceProperty("password", dbPassword);

        // MySQL为了性能的情况下使用设定
        config.addDataSourceProperty("cachePrepStmts", hkCachePrepStmts);
        config.addDataSourceProperty("prepStmtCacheSize", hkPrepStmtCacheSize);
        config.addDataSourceProperty("prepStmtCacheSqlLimit", hkPrepStmtCacheSqlLimit);
        config.addDataSourceProperty("useServerPrepStmts", hkUseServerPrepStmts);
        config.setMaxLifetime(hkMaxLifetime);
        config.setAutoCommit(hkIsAutoCommit);
        try {
            dataSource = new HikariDataSource(config);
        }catch (Exception e) {
            System.out.println("DB server is not running!");
            e.printStackTrace();
        }
    }

    /**
     * 从连接池中获取连接
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            System.out.println("connect to DB server error!");
            e.printStackTrace();
            dataSource.resumePool();
        }
        return null;
    }

    public void evictConnection(Connection connection) throws SQLException {
            dataSource.evictConnection(connection);
    }

    /**
     * 销毁连接池
     */
    public boolean stop() throws SQLException {
        dataSource.close();
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VCHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值