1、开启PSCache
// 开启 dataSource.setPoolPreparedStatements(true); dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
configFromProperty加载配置文件的时候,设置每个连接指定的PSCache缓存的大小,并且配置poolPreparedStatements变量为true,所以如果要开启PSCache除了指定setPoolPreparedStatements=true,还需要指定每个连接的缓存大小配置
{ String property = properties.getProperty("druid.maxPoolPreparedStatementPerConnectionSize"); if (property != null && property.length() > 0) { try { int value = Integer.parseInt(property); this.setMaxPoolPreparedStatementPerConnectionSize(value); } catch (NumberFormatException e) { LOG.error("illegal property 'druid.maxPoolPreparedStatementPerConnectionSize'", e); } } }
public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) { if (maxPoolPreparedStatementPerConnectionSize > 0) { this.poolPreparedStatements = true; } else { this.poolPreparedStatements = false; } this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize; }
预编译sql的时候如果开启了PSCache,会对cache进行初始化
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from depart where id =?");
stmt.setInt(1,1);
ResultSet resultSet = stmt.executeQuery();
在获取缓存的时候通过key来获取,这个key是PreparedStatementKey一个静态内部类
通过key获取PreparedStatementHolder对象,其中这个map是一个LRUCache,即清除缓存的策略是不常用的缓存会被清除,也是继承LinkedHashMap实现的缓存策略
PreparedStatementHolder holder = map.get(key);
public PreparedStatementHolder get(PreparedStatementKey key) throws SQLException {
// 获取到缓存数据
PreparedStatementHolder holder = map.get(key);
if (holder != null) {
if (holder.isInUse() && (!dataSource.isSharePreparedStatements())) {
return null;
}
// 命中缓存记录数 + 1
holder.incrementHitCount();
dataSource.incrementCachedPreparedStatementHitCount();
if (holder.isEnterOracleImplicitCache()) {
OracleUtils.exitImplicitCacheToActive(holder.statement);
}
} else {
dataSource.incrementCachedPreparedStatementMissCount();
}
return holder;
}
2、map.get(key)
get(key)时会调用当前key的hashcode,PreparedStatementKey对象也是重写了hashCode(),这个方法会把PreparedStatementKey实例的所有成员变量都进行累加,也就是在get(key)的时候要比较当前实例实例的所有变量值
public static class PreparedStatementKey {
//省略
。。。
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sql == null) ? 0 : sql.hashCode());
result = prime * result + ((catalog == null) ? 0 : catalog.hashCode());
result = prime * result + ((methodType == null) ? 0 : methodType.hashCode());
result = prime * result + resultSetConcurrency;
result = prime * result + resultSetHoldability;
result = prime * result + resultSetType;
result = prime * result + autoGeneratedKeys;
result = prime * result + Arrays.hashCode(columnIndexes);
result = prime * result + Arrays.hashCode(columnNames);
System.out.println(result);
return result;
}
public String getSql() {
return sql;
}
}