Druid源码分析(九) PoolPreparedStatements

PreparedStatements是什么

通常我们的一条sql在db接收到最终执行完毕返回可以分为下面:

  1. 词法和语义解析
  2. 优化sql语句,制定执行计划
  3. 执行并返回结果

但是如果每次都需要经过上面的词法语义解析、语句优化、制定执行计划等,则效率就明显不行了。

预编译的statement

所谓预编译语句就是将这类语句中的值用占位符替代,可以视为将sql语句模板化或者说参数化,一般称这类语句叫Prepared Statements或者Parameterized Statements 预编译语句的优势在于归纳为:<B>一次编译、多次运行,省去了解析优化等过程;此外预编译语句能防止sql注入。</B>

什么是 PoolPreparedStatements

从名字上可以看出:池化PreparedStatements对象 就是PoolPreparedStatements 我好想说了句废话~但事实就是这样.

<font color=red>PoolPreparedStatements只对oracle有效</font>

配置参数

配置 缺省值 说明
poolPreparedStatements false 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭
maxPoolPreparedStatementPerConnectionSize -1 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100

什么时候从PoolPreparedStatements获取PreparedStatements对象

一切的入口从 conn.prepareStatement()开始


Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT 1");
ResultSet rs = stmt.executeQuery();

还是他: DruidPooledConnection

当你使用了DruidDataSource,并且使用了PreparedStatement执行sql,就会调用DruidPooledConnectionprepareStatement实现. <font color=red>需要注意即便PsCache中没有,也不再执行sql阶段putPsCache</font>

  1. 检查closed,disable,null等状态,还有是否开启了asyncCloseEnabled,是的话得上lock
  2. 新建一个PsCache查询的key,因为PsCache是一个哈希结构
  3. 判断是否开启了poolPreparedStatements
  4. 开启了从PsCache中获取已经提前创建的PreparedStatementsHolder,其实就是获取PreparedStatement 因为是1对1的关系
  5. 添加对PreparedStatementsHolder的追踪信息
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
    // 检查状态
    checkState();

    // 获取一个 PreparedStatement实例 PreparedStatementHolder : PreparedStatement 1对1关系
    // 在PreparedStatement基础上封装了一层,组合关系
    PreparedStatementHolder stmtHolder = null;
    PreparedStatementKey key = new PreparedStatementKey(sql, getCatalog(), MethodType.M1);

    // 判断是否开启了 psCache
    boolean poolPreparedStatements = holder.isPoolPreparedStatements();

    if (poolPreparedStatements) {
        // holder.getStatementPool() 是一个 LRUCache结构,避免了无穷创建.
        // 如果这个LRUCache的HashMap的size 大于了maxPoolPreparedStatementPerConnectionSize
        // 如果使用了inUse()方法会大于0 返回true,避免线程安全问题
        stmtHolder = holder.getStatementPool().get(key);
    }

    if (stmtHolder == null) {
        // 没有从psCache获得PreparedStatements对象
        try {
            // 那么就new一个加进去吧
            stmtHolder = new PreparedStatementHolder(key, conn.prepareStatement(sql));
            holder.getDataSource().incrementPreparedStatementCount();
        } catch (SQLException ex) {
            handleException(ex, sql);
        }
    }

    // 初始化一些 statement的参数 超时时间,inUseCount++;
    initStatement(stmtHolder);

    // 添加链路追踪吧
    DruidPooledPreparedStatement rtnVal = new DruidPooledPreparedStatement(this, stmtHolder);
    holder.addTrace(rtnVal);
    return rtnVal;
}

对象什么时候进入PoolPreparedStatements

当调用 stmt.close(); 方法时,会执行DruidPooledPreparedStatementclose方法,关闭时将preparedStatements 塞到PoolPreparedStatements

public void closePoolableStatement(DruidPooledPreparedStatement stmt)

// 省略很多逻辑..直接看put的入口
if (stmt.isPooled() && holder.isPoolPreparedStatements() && stmt.exceptionCount == 0) {
    // close的时候会put
    holder.getStatementPool().put(stmtHolder);

    stmt.clearResultSet();
    holder.removeTrace(stmt);

    stmtHolder.setFetchRowPeak(stmt.getFetchRowPeak());

    stmt.setClosed(true); // soft set close
} 

checkState 方法

主要调用了checkStateInternal方法,但是判断了配置项 asyncCloseEnabled.异步关闭的操作会存在安全问题. 所以对于异步关闭连接的请求进行了锁,最终都执行了 checkStateInternal()

public void checkState() throws SQLException {
    final boolean asyncCloseEnabled;
    // 是否 打开异步关闭连接
    if (holder != null) {
        asyncCloseEnabled = holder.getDataSource().isAsyncCloseConnectionEnable();
    } else {
        asyncCloseEnabled = false;
    }

    // 如果打开了这个开关,需要锁住再执行,这里代表异步关闭会有并发问题
    if (asyncCloseEnabled) {
        lock.lock();
        try {
            checkStateInternal();
        } finally {
            lock.unlock();
        }
    } else {
        checkStateInternal();
    }
}
isAsyncCloseConnectionEnable 方法

获取当前DruidDataSourceconnection <B>开启异步关闭连接</B> 配置

public boolean isAsyncCloseConnectionEnable() {
  // 如果开启了强制回收策略
  if (isRemoveAbandoned()) {
      // 开启异步关闭连接
      return true;
  }
  
  // 返回asyncCloseConnectionEnable 默认值false
  return asyncCloseConnectionEnable;
}

checkStateInternal方法

内部检查状态的方法, checkState真正要做的事,都是连接的状态判断

  1. closed -> 已经关闭的连接一定是程序出错了
  2. disable -> 无效的连接 肯定也是不正确的状态
  3. holder == null -> holder对象都没了,逻辑不抛错,后面也肯定错了.这种情况有可能是被gc了,但是几乎不可能,算是代码严谨,健壮性吧
private void checkStateInternal() throws SQLException {
    if (closed) {
        if (disableError != null) {
            throw new SQLException("connection closed", disableError);
        } else {
            throw new SQLException("connection closed");
        }
    }

    if (disable) {
        if (disableError != null) {
            throw new SQLException("connection disabled", disableError);
        } else {
            throw new SQLException("connection disabled");
        }
    }

    if (holder == null) {
        if (disableError != null) {
            throw new SQLException("connection holder is null", disableError);
        } else {
            throw new SQLException("connection holder is null");
        }
    }
}

LRUCache 底层数据结构

LRUCache即最近最少使用策略,

private final LRUCache                map;

继承了LinkedHashMap类 是一个key,value的结构

public class LRUCache extends LinkedHashMap<PreparedStatementKey, PreparedStatementHolder> {

    private static final long serialVersionUID = 1L;

    public LRUCache(int maxSize){
        super(maxSize, 0.75f, true);
    }

    protected boolean removeEldestEntry(Entry<PreparedStatementKey, PreparedStatementHolder> eldest) {
        boolean remove = (size() > dataSource.getMaxPoolPreparedStatementPerConnectionSize());

        if (remove) {
            closeRemovedStatement(eldest.getValue());
        }

        return remove;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容