Java 数据连接池Druid

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java 数据连接池Druid

晴天哥_王志   2022-05-28 我要评论

开篇

Druid号称是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能。作为日常使用较多的数据库连接组件,纯粹个人兴趣研究下理解下的实现原理。

理解一个工具组件最好的方式就是进行 debug,这里建议大家下载下参考连接中的 druid demo,修改下具体的数据库连接参数就可以直接进行调试跟踪。

之所以强调 Demo 的重要性,在于通过 demo 能够跟踪所有的执行流程,有了 Demo 剩下的事情只要花时间都能很好的梳理。

Druid的调试

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 的连接地址信息。

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 的执行。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们