mysql机制及错误原因:当连接闲置超过八小时后,mysql会自动断开连接,此时连接失效,但是数据库认为此时连接依然有效,连接的时候发现失效,报错。
解决办法:增加对连接池中连接的测试/验证,防止数据库认为连接已死而Web应用服务器认为连接还有效
添加参数:
testOnBorrow:检测池里连接的可用性 设置为true是会见降低性能
validationQuery:验证数据库连接的查询语句
testWhileIdle:建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://xxx.xxx.xx.xx:3306/omslocal?useSSL=false&autoReconnect=true&testWhileIdle=true&testOnBorrow=true&validationQuery=select 1"; //考虑性能,此处请酌情修改
public static final String DBUSER = "xxx";
public static final String PASSWORD = "xxx";
public static java.sql.Connection connection = null;
public static java.sql.PreparedStatement preparedStatement = null;
public static java.sql.ResultSet resultSet = null;
public static String getConnection() {
try {
Class.forName(DBDRIVER);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(DBURL, DBUSER, PASSWORD);
return "success";
} catch (ClassNotFoundException e) {
return "ClassNotFoundException";
} catch (SQLException e) {
return e.toString();
}
}
参考配置:
<!--initialSize: 初始化连接-->
<property name="initialSize" value="5"/>
<!--maxIdle: 最大空闲连接-->
<property name="maxIdle" value="10"/>
<!--minIdle: 最小空闲连接-->
<property name="minIdle" value="5"/>
<!--maxActive: 最大连接数量-->
<property name="maxActive" value="15"/>
<!--removeAbandoned: 是否自动回收超时连接-->
<property name="removeAbandoned" value="true"/>
<!--removeAbandonedTimeout: 超时时间(以秒数为单位)-->
<property name="removeAbandonedTimeout" value="180"/>
<!--maxWait: 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒-->
<property name="maxWait" value="3000"/>
<property name="validationQuery">
<value>SELECT 1</value>
</property>
<property name="testOnBorrow">
<value>true</value>
</property>