當 Druid 連接池中的連接超時時,可以通過配置相關的參數來處理超時連接。以下是一些處理超時連接的常見方法:
spring.datasource.druid.maxWait=10000
spring.datasource.druid.removeAbandoned=true
spring.datasource.druid.removeAbandonedTimeout=180
DruidDataSource dataSource = (DruidDataSource) dataSource;
int removeAbandonedTimeout = dataSource.getRemoveAbandonedTimeout();
int abandonedConnectionCount = dataSource.getRemoveAbandonedCount();
if (removeAbandonedTimeout > 0 && abandonedConnectionCount > 0) {
Date now = new Date();
List<DruidPooledConnection> abandonedConnections = new ArrayList<>();
for (DruidPooledConnection connection : dataSource.getConnections()) {
if ((now.getTime() - connection.getLastActiveTimeMillis()) > removeAbandonedTimeout) {
abandonedConnections.add(connection);
}
}
for (DruidPooledConnection connection : abandonedConnections) {
dataSource.removeAbandoned(connection);
}
}
通過以上方法可以有效處理 Druid MyBatis 超時連接的問題,保證應用程序的穩定性和性能。