开篇
Druid号称是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能。作为日常使用较多的数据库连接组件,纯粹个人兴趣研究下理解下的实现原理。
理解一个工具组件最好的方式就是进行 debug,这里建议大家下载下参考连接中的 druid demo,修改下具体的数据库连接参数就可以直接进行调试跟踪。
之所以强调 Demo 的重要性,在于通过 demo 能够跟踪所有的执行流程,有了 Demo 剩下的事情只要花时间都能很好的梳理。
Druid的调试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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 |
基础的配置信息如上,核心在于 JDBC 的连接地址信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class DruidDataSourceTest {
@Test public void save() throws SQLException { // 创建sql String sql = "insert into demo_user values(null,?,?,?,?,?)" ; Connection connection = null ; PreparedStatement statement = null ; try { // 获得连接 connection = JDBCUtils.getConnection(); // 开启事务设置非自动提交 connection.setAutoCommit( false ); // 获得Statement对象 statement = connection.prepareStatement(sql); // 设置参数 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 ); // 执行 statement.executeUpdate(); // 提交事务 connection.commit(); } finally { // 释放资源 JDBCUtils.release(connection, statement, null ); } } } |
核心步骤获获取 Connection 并设置并通过 Connection 设置statement,最后通过statement进行 SQL 的执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
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( "创建数据源失败" , e); } }
/** * <p>获取数据库连接对象的方法,线程安全</p> * @return: Connection */ public static Connection getConnection() throws SQLException { // 从当前线程中获取连接对象 Connection connection = tl.get(); // 判断为空的话,创建连接并绑定到当前线程 if (connection == null ) { connection = createConnection(); tl.set(connection); } return connection; }
/** * <p>创建数据库连接</p> * @return: Connection * @throws SQLException */ private static Connection createConnection() throws SQLException { Connection conn = null ; // 获得连接 conn = dataSource.getConnection(); return conn; } } |
通过DruidDataSourceFactory创建 DataSource。 通过DataSource获取 Connection。
参考
druid源码仓库
druid demo
到此这篇关于Java实现数据连接池Druid举例的文章就介绍到这了,更多相关Java 数据连接池Druid内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://www.jianshu.com/p/dfdee14ab0c5
查看更多关于Java实现数据连接池Druid举例的详细内容...