当前位置:网站首页>Analysis and solution of connection failure caused by MySQL using replicationconnection
Analysis and solution of connection failure caused by MySQL using replicationconnection
2022-06-23 12:43:00 【InfoQ】
The problem background

The main configurations involved are as follows :
if (testWhileIdle) {
final DruidConnectionHolder holder = poolableConnection.holder;
long currentTimeMillis = System.currentTimeMillis();
long lastActiveTimeMillis = holder.lastActiveTimeMillis;
long lastExecTimeMillis = holder.lastExecTimeMillis;
long lastKeepTimeMillis = holder.lastKeepTimeMillis;
if (checkExecuteTime
&& lastExecTimeMillis != lastActiveTimeMillis) {
lastActiveTimeMillis = lastExecTimeMillis;
}
if (lastKeepTimeMillis > lastActiveTimeMillis) {
lastActiveTimeMillis = lastKeepTimeMillis;
}
long idleMillis = currentTimeMillis - lastActiveTimeMillis;
long timeBetweenEvictionRunsMillis = this.timeBetweenEvictionRunsMillis;
if (timeBetweenEvictionRunsMillis <= 0) {
timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
}
if (idleMillis >= timeBetweenEvictionRunsMillis
|| idleMillis < 0 // unexcepted branch
) {
boolean validate = testConnectionInternal(poolableConnection.holder, poolableConnection.conn);
if (!validate) {
if (LOG.isDebugEnabled()) {
LOG.debug("skip not validate connection.");
}
discardConnection(poolableConnection.holder);
continue;
}
}
}
The essential reason
Cause analysis
mysql-jdbc in , The database driver handles the connection

public static ReplicationConnection createProxyInstance(List<String> masterHostList, Properties masterProperties, List<String> slaveHostList,
Properties slaveProperties) throws SQLException {
ReplicationConnectionProxy connProxy = new ReplicationConnectionProxy(masterHostList, masterProperties, slaveHostList, slaveProperties);
return (ReplicationConnection) java.lang.reflect.Proxy.newProxyInstance(ReplicationConnection.class.getClassLoader(), INTERFACES_TO_PROXY, connProxy);
}
ReplicationConnectionProxy An important part of

ReplicationConnection Proxy object processing

druid Data source pair MySQ Inspection of connections
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
if (conn.isClosed()) {
return false;
}
if (usePingMethod) {
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxy) {
conn = ((ConnectionProxy) conn).getRawObject();
}
if (clazz.isAssignableFrom(conn.getClass())) {
if (validationQueryTimeout <= 0) {
validationQueryTimeout = DEFAULT_VALIDATION_QUERY_TIMEOUT;
}
try {
ping.invoke(conn, true, validationQueryTimeout * 1000);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof SQLException) {
throw (SQLException) cause;
}
throw e;
}
return true;
}
}
String query = validateQuery;
if (validateQuery == null || validateQuery.isEmpty()) {
query = DEFAULT_VALIDATION_QUERY;
}
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
if (validationQueryTimeout > 0) {
stmt.setQueryTimeout(validationQueryTimeout);
}
rs = stmt.executeQuery(query);
return true;
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
}
}
public MySqlValidConnectionChecker(){
try {
clazz = Utils.loadClass("com.mysql.jdbc.MySQLConnection");
if (clazz == null) {
clazz = Utils.loadClass("com.mysql.cj.jdbc.ConnectionImpl");
}
if (clazz != null) {
ping = clazz.getMethod("pingInternal", boolean.class, int.class);
}
if (ping != null) {
usePingMethod = true;
}
} catch (Exception e) {
LOG.warn("Cannot resolve com.mysql.jdbc.Connection.ping method. Will use 'SELECT 1' instead.", e);
}
configFromProperties(System.getProperties());
}
@Override
public void configFromProperties(Properties properties) {
String property = properties.getProperty("druid.mysql.usePingMethod");
if ("true".equals(property)) {
setUsePingMethod(true);
} else if ("false".equals(property)) {
setUsePingMethod(false);
}
}
Solution
Adjust the dependent version
Modify the read / write separation implementation
expand mysql-jdbc drive
be based on druid, expand MySQL Connection check
public class MySqlReplicationCompatibleValidConnectionChecker extends MySqlValidConnectionChecker {
private static final Log LOG = LogFactory.getLog(MySqlValidConnectionChecker.class);
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
if (conn.isClosed()) {
return false;
}
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxy) {
conn = ((ConnectionProxy) conn).getRawObject();
}
if (conn instanceof ReplicationConnection) {
try {
((ReplicationConnection) conn).ping();
LOG.info("validate connection success: connection=" + conn.toString());
return true;
} catch (SQLException e) {
LOG.error("validate connection error: connection=" + conn.toString(), e);
throw e;
}
}
return super.isValidConnection(conn, validateQuery, validationQueryTimeout);
}
}
边栏推荐
- C # learning (advanced course) day14 - features
- R语言dplyr包arrange函数排序dataframe数据、通过多个数据列排序dataframe数据(默认是升序排序)
- What are the risks of opening a mobile account? Is it safe to open an account?
- C#学习(高级课程)Day14——特性
- DuPont analysis: what is the investment value of Anyang Iron and Steel Co., Ltd?
- MySQL使用ReplicationConnection导致的连接失效分析与解决
- UI框架
- M & A and capital increase may be expected to start Neusoft's new momentum?
- Follow the promotional music MV of domestic tour in Thailand and travel to Bangkok like local people
- Basic data type and corresponding packing class
猜你喜欢

Qt5 knowledge: some key points of signals and slots

ROS知识:点云文件.pcd格式

M & A and capital increase may be expected to start Neusoft's new momentum?

DevEco Device Tool 助力OpenHarmony设备开发

Linked list 5 - 234 Palindrome linked list

Slam Laser 2D (en utilisant Laser Scan matcher)

解决:Argument type ‘String‘ expected to be an instance of a class or class-constrained type
![解决“Thread 1: “-[*.CollectionNormalCellView isSelected]: unrecognized selector sent to instance 0x7f”](/img/35/65511c49eca5ae8a1896d776b479d9.jpg)
解决“Thread 1: “-[*.CollectionNormalCellView isSelected]: unrecognized selector sent to instance 0x7f”

Based on your work experience, talk about the quality system construction in software testing

ROS knowledge: point cloud files PCD format
随机推荐
对象池框架
Synergetic process
LinkedList 5-141. Circular linked list
ROS knowledge: point cloud files PCD format
How to test the third-party payment interface?
What should I do if a serious bug occurs within the scope of my own test and I am about to go online?
An idea of using keep alive to cache data in vue3 form pages
【UVM入门 ===> Episode_7 】~ sequence、sequence item、sequencer、driver
Ablebits Ultimate Suite for Excel
QT knowledge: using the qgraphicspixmapitem class
群晖万兆网络配置与测试
Unity learning day14 -- collaboration and WWW
涉及第三方支付接口,怎么测?
SQL adds the problem of duplicate table records.
TT-SLAM:用于平面环境的密集单目SLAM(IEEE 2021)
ROS察微【57】:配置手臂机器人来抓东西
R语言dplyr包arrange函数排序dataframe数据、通过多个数据列排序dataframe数据(默认是升序排序)
ROS知识:点云文件.pcd格式
Unity学习Day14--协程和WWW
Deep thinking: in-depth analysis of some scenes in Gaia Altman and the philosophy and perception reflected