Java實(shí)現(xiàn)數(shù)據(jù)連接池Druid舉例
開篇
Druid號(hào)稱是Java語言中最好的數(shù)據(jù)庫連接池,并且能夠提供強(qiáng)大的監(jiān)控和擴(kuò)展功能。作為日常使用較多的數(shù)據(jù)庫連接組件,純粹個(gè)人興趣研究下理解下的實(shí)現(xiàn)原理。
理解一個(gè)工具組件最好的方式就是進(jìn)行 debug,這里建議大家下載下參考連接中的 druid demo,修改下具體的數(shù)據(jù)庫連接參數(shù)就可以直接進(jìn)行調(diào)試跟蹤。
之所以強(qiáng)調(diào) Demo 的重要性,在于通過 demo 能夠跟蹤所有的執(zhí)行流程,有了 Demo 剩下的事情只要花時(shí)間都能很好的梳理。
Druid的調(diào)試
url=jdbc:mysql://localhost:3306/github_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=true username=root password=123456 name=zzs001 driverClassName=com.mysql.cj.jdbc.Driver initialSize=4 maxActive=8 minIdle=0 maxWait=-1 poolPreparedStatements=false maxOpenPreparedStatements=10 validationQuery=select 1 from dual validationQueryTimeout=-1 testOnBorrow=false testOnReturn=false testWhileIdle=true timeBetweenEvictionRunsMillis=-1 minEvictableIdleTimeMillis=1800000 defaultAutoCommit=true defaultReadOnly=false defaultTransactionIsolation=REPEATABLE_READ defaultCatalog=github_demo removeAbandoned=false removeAbandonedTimeoutMillis=300*1000 logAbandoned=true filters=log4j,wall,mergeStat connectionProperties=druid.useGlobalDataSourceStat=true;druid.stat.logSlowSql=true;druid.stat.slowSqlMillis=5000 accessToUnderlyingConnectionAllowed=false init=true
基礎(chǔ)的配置信息如上,核心在于 JDBC 的連接地址信息。
public class DruidDataSourceTest {
? ? @Test
? ? public void save() throws SQLException {
? ? ? ? // 創(chuàng)建sql
? ? ? ? String sql = "insert into demo_user values(null,?,?,?,?,?)";
? ? ? ? Connection connection = null;
? ? ? ? PreparedStatement statement = null;
? ? ? ? try {
? ? ? ? ? ? // 獲得連接
? ? ? ? ? ? connection = JDBCUtils.getConnection();
? ? ? ? ? ? // 開啟事務(wù)設(shè)置非自動(dòng)提交
? ? ? ? ? ? connection.setAutoCommit(false);
? ? ? ? ? ? // 獲得Statement對(duì)象
? ? ? ? ? ? statement = connection.prepareStatement(sql);
? ? ? ? ? ? // 設(shè)置參數(shù)
? ? ? ? ? ? statement.setString(1, "zzf003");
? ? ? ? ? ? statement.setInt(2, 18);
? ? ? ? ? ? statement.setDate(3, new Date(System.currentTimeMillis()));
? ? ? ? ? ? statement.setDate(4, new Date(System.currentTimeMillis()));
? ? ? ? ? ? statement.setBoolean(5, false);
? ? ? ? ? ? // 執(zhí)行
? ? ? ? ? ? statement.executeUpdate();
? ? ? ? ? ? // 提交事務(wù)
? ? ? ? ? ? connection.commit();
? ? ? ? } finally {
? ? ? ? ? ? // 釋放資源
? ? ? ? ? ? JDBCUtils.release(connection, statement, null);
? ? ? ? }
? ? }
}核心步驟獲獲取 Connection 并設(shè)置并通過 Connection 設(shè)置statement,最后通過statement進(jìn)行 SQL 的執(zhí)行。
public class JDBCUtils {
? ? private static DataSource dataSource;
? ? private static ThreadLocal<Connection> tl = new ThreadLocal<>();
? ? private static final Log log = LogFactory.getLog(JDBCUtils.class);
? ? static {
? ? ? ? init();
? ? }
? ? private static void init() {
? ? ? ? Properties properties = new Properties();
? ? ? ? InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
? ? ? ? try {
? ? ? ? ? ? properties.load(in);
? ? ? ? ? ? dataSource = DruidDataSourceFactory.createDataSource(properties);
? ? ? ? } catch(Exception e) {
? ? ? ? ? ? throw new RuntimeException("創(chuàng)建數(shù)據(jù)源失敗", e);
? ? ? ? }
? ? }
? ? /**
? ? ?* <p>獲取數(shù)據(jù)庫連接對(duì)象的方法,線程安全</p>
? ? ?* @return: Connection
? ? ?*/
? ? public static Connection getConnection() throws SQLException {
? ? ? ? // 從當(dāng)前線程中獲取連接對(duì)象
? ? ? ? Connection connection = tl.get();
? ? ? ? // 判斷為空的話,創(chuàng)建連接并綁定到當(dāng)前線程
? ? ? ? if(connection == null) {
? ? ? ? ? ? connection = createConnection();
? ? ? ? ? ? tl.set(connection);
? ? ? ? }
? ? ? ? return connection;
? ? }
? ? /**
? ? ?* <p>創(chuàng)建數(shù)據(jù)庫連接</p>
? ? ?* @return: Connection
? ? ?* @throws SQLException?
? ? ?*/
? ? private static Connection createConnection() throws SQLException {
? ? ? ? Connection conn = null;
? ? ? ? // 獲得連接
? ? ? ? conn = dataSource.getConnection();
? ? ? ? return conn;
? ? }
}- 通過DruidDataSourceFactory創(chuàng)建 DataSource。
- 通過DataSource獲取 Connection。
參考
到此這篇關(guān)于Java實(shí)現(xiàn)數(shù)據(jù)連接池Druid舉例的文章就介紹到這了,更多相關(guān)Java 數(shù)據(jù)連接池Druid內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot 基于Tomcat容器的自啟動(dòng)流程分析
這篇文章主要介紹了springboot 基于Tomcat容器的自啟動(dòng)流程分析,Spring通過注解導(dǎo)入Bean大體可分為四種方式,我們主要來說Import的兩種實(shí)現(xiàn)方法,需要的朋友可以參考下2020-02-02
Java中使用SQLite數(shù)據(jù)庫的實(shí)現(xiàn)示例
SQLite是一種嵌入式數(shù)據(jù)庫引擎,可以在各種平臺(tái)上使用,本文主要介紹了Java中使用SQLite數(shù)據(jù)庫的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
logback的isDebugEnabled日志配置級(jí)別源碼解析
這篇文章主要為大家介紹了logback的isDebugEnabled日志配置級(jí)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
java調(diào)用shell腳本及注意事項(xiàng)說明
這篇文章主要介紹了java調(diào)用shell腳本及注意事項(xiàng)說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式
在實(shí)際開發(fā)中經(jīng)常會(huì)遇到在spring容器加載完某個(gè)bean之后,需要執(zhí)行一些業(yè)務(wù)代碼的場(chǎng)景,本文給大家介紹Spring創(chuàng)建Bean完成后執(zhí)行指定代碼的幾種實(shí)現(xiàn)方式,感興趣的朋友一起看看吧2024-01-01
java獲取本地文件的多種方式實(shí)現(xiàn)與比較
這篇文章主要為大家詳細(xì)介紹了java獲取本地文件的多種方式實(shí)現(xiàn)與結(jié)果比較,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11

