在DB故障转移场景下使用HikariCP



我正在考虑将hikariCP与AWS RDS一起使用,并希望澄清有关数据库故障转移场景的hikariCP的一些规范。

  1. HikariCP是否总是在连接从池中取出并在连接被应用程序使用之前验证连接?
    根据这句话"这是将在从池中向您提供连接之前执行的查询,以验证到数据库的连接仍然是活动的。"在https://github.com/brettwooldridge/HikariCP中,我猜总是执行连接验证。
    但是,这个注释似乎表明连接验证并不总是执行。

  2. 如果总是执行上面提到的连接验证,当执行的连接验证失败时,是立即向应用程序抛出异常,还是从池中拾取另一个连接而不抛出异常?

  3. 如果从池中捡起另一个连接而没有抛出异常,HikariCP是否有此连接拾取的超时设置?
    我想connectionTimeout可能是那个。

将这些参数添加到jvm中进行DNS刷新-Dnetworkaddress.cache.ttl ="60";-Dnetworkaddress.cache.negative.ttl ="10";-Dsun.net.inetaddr.ttl = 60 -Dsun.net.inetaddr.negative.ttl = 1

checkForIpChange并定期退出连接

private void checkForIpChange(HikariDataSource dataSource) {
try {
String ip = getIp(dataSource.getJdbcUrl());
if (Objects.isNull(dataSourceIpMap.get(dataSource))) {
dataSourceIpMap.put(dataSource, ip);
} else if (!StringUtils.equals(ip, dataSourceIpMap.get(dataSource))) {
log.info("writer ip changed, old is {} and new is {}", dataSourceIpMap.get(dataSource), ip);
evictConnections(dataSource);
dataSourceIpMap.put(dataSource, ip);
}
} catch (Exception e) {
log.error("Caught exception in cname check", e);
}
}
/**
* soft eviction will add a new entry in the pool if the pool is not suspended, so suspend it
* connection count is transient so take 10 zero samples to ensure full eviction
* 60 sec wait time if all this does not work
*
* @param dataSource
*/
private void evictConnections(HikariDataSource dataSource) {
HikariPoolMXBean pool = dataSource.getHikariPoolMXBean();
if (pool != null) {
log.info("Active connection count is : {}, idle connection count is {} and total connection count is {}",
pool.getActiveConnections(), pool.getIdleConnections(), pool.getTotalConnections());
log.info("suspending pool");
pool.suspendPool();
int zeroConnectionCount = 0;
long currentTimeMillis = System.currentTimeMillis();
for (long time = currentTimeMillis; time < currentTimeMillis + MAX_EVICT_WAIT_TIME_MILLS; time = time + 100) {
pool.softEvictConnections();
if (pool.getTotalConnections() == 0) {
zeroConnectionCount++;
if (zeroConnectionCount >= ZERO_CONNECTION_VALIDATION_COUNT) {
log.info("ZeroConnectionCount encountered {} times, so exiting loop", zeroConnectionCount);
break;
}
}
}
log.info("resuming pool");
pool.resumePool();
}
}
private String getIp(String url) throws URISyntaxException, UnknownHostException {
URI aURL = new URI(url);
aURL = new URI(aURL.getSchemeSpecificPart());
InetAddress address = InetAddress.getByName(aURL.getHost());
return address.getHostAddress();
}

相关内容

  • 没有找到相关文章