log4j 数据库断连接解决办法

时间:2021-11-17 00:05:34

1、用自定义的JDBCAppender,获取连接后校验下合法性,非法的话重新取得连接。

package org.pentaho.di.dxt.common.Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.jdbc.JDBCAppender;

public class DxtJdbcAppender extends JDBCAppender {
@Override
protected Connection getConnection() throws SQLException {
if (!DriverManager.getDrivers().hasMoreElements())
setDriver("sun.jdbc.odbc.JdbcOdbcDriver");

if ((null != connection) && !connection.isValid(2)) {
connection = null;
}

if (connection == null) {
connection = DriverManager.getConnection(databaseURL, databaseUser, databasePassword);
}

return connection;
}
}

2、log4j.properties中指定database为自定义的这个appender

########################
# JDBC Appender
#######################
log4j.appender.DATABASE = org.pentaho.di.dxt.common.Util.DxtJdbcAppender