1. 程式人生 > >Hikari java資料庫連線池實戰

Hikari java資料庫連線池實戰

環境InterlliJ2016.3  MySQL5.7.12

gradle依賴庫:

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
compile 'org.slf4j:slf4j-log4j12:1.7.21'compile 'mysql:mysql-connector-java:5.1.39'compile 'com.zaxxer:HikariCP:2.4.6'
}

配置檔案db.properties

db_url= 192.168.199.132
db_port = 3306
db_name = mind db_max_conn = 100 db_username = root db_password = root

DBService.Java:

package com.mind.core.db.impl;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 final String DB_CONFIG_FILE = "/db.properties";
// 資料庫連線數 private short db_max_conn = 0; // 資料庫伺服器addr private String db_url = null; // 資料庫連線埠 private short db_port = 0; // 資料庫名稱 private String db_name = null; // 資料庫登入使用者名稱 private String db_username = null; // 資料庫登入密碼 private String db_password = null; // 資料庫連線 private Connection connection; private static DBService dBService; public static DBService getInstance(){ if (dBService == null) { dBService = new DBService(); } return dBService; } public void start() throws IOException, SQLException { Properties properties = new Properties(); InputStream in = DBService.class.getClass().getResourceAsStream(DB_CONFIG_FILE); properties.load(in); db_max_conn = Short.valueOf(properties.getProperty("db_max_conn")); db_url = String.valueOf(properties.getProperty("db_url")); db_port = Short.valueOf(properties.getProperty("db_port")); db_name = String.valueOf(properties.getProperty("db_name")); db_username = String.valueOf(properties.getProperty("db_username")); db_password = String.valueOf(properties.getProperty("db_password")); if (db_url == null || db_url.length() == 0) { logger.error("配置的資料庫ip地址錯誤!"); System.exit(0); } HikariConfig config = new HikariConfig(); config.setMaximumPoolSize(db_max_conn); config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource"); config.addDataSourceProperty("serverName", db_url); config.addDataSourceProperty("port", db_port); config.addDataSourceProperty("databaseName", db_name); config.addDataSourceProperty("user", db_username); config.addDataSourceProperty("password", db_password); HikariDataSource dataSource = new HikariDataSource(config); // // 也可以這樣寫 // config.setDriverClassName("com.mysql.jdbc.Driver"); // config.setJdbcUrl("jdbc:mysql://"+ db_url +"/" + db_name + "?useUnicode=true&characterEncoding=utf8&useSSL=false"); // config.setUsername(db_username); // config.setPassword(db_password); // config.addDataSourceProperty("cachePrepStmts", "true"); // config.addDataSourceProperty("prepStmtCacheSize", "250"); // config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); // // 設定連線超時為8小時 // config.setConnectionTimeout(8 * 60 * 60); // HikariDataSource dataSource = new HikariDataSource(config);}
    public Connection getConnection() throws SQLException {
        try {
            return dataSource.getConnection();
} catch (SQLException e) {
            e.printStackTrace();
dataSource.resumePool();
            return null;
}    }

    public boolean stop() throws SQLException {
        dataSource.close();
        return true;
}
}

DBServiceTest.java

package com.mind.core.db.impl;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * Created by Lovell on 16/6/25.
 */
public class DBServiceTest {
    public static void main(String[] args) throws IOException, SQLException {
        DBSservice.getInstance().start();

        // statement用來執行SQL語句
Statement statement = DBService.getInstance().getConnection().createStatement();
// 要執行的SQL語句id和content是表review中的項。
String sql = "select * from login where name='Lovell' and password='123456'";
// 得到結果
ResultSet rs = statement.executeQuery(sql);
        if(rs.next()){
            System.out.println("Logon");
}else{
            System.out.println("Login Faild");
}
        rs.close();
}
}