Druid动态数据源配置 主要是继承AbstractRoutingDataSource再通过AOP来实现动态数据源切换.
下面给大家介绍Druid动态配置数据源重复刷错误日志问题,具体内容如下所示:
问题描述
功能需求:使用druid数据库连接池实现 动态的配置数据源功能:IP、端口、用户名、密码都是用户页面手动输入,可以测试连接,保存数据源。
问题说明:既然是用户自己配置的数据源,就无法避免输入错误,连接失败等情况。
预期情况:用户输入的配置错误,测试连接时,会返回连接失败的信息。
实际情况:数据源测试连接,连接失败后:
后台一直打印错误信息,一直自动重连
方法被阻塞无返回信息,导致前端页面一直处于等待状态
【错误信息】:
com.alibaba.druid.pool.DruidDataSource-create connection SQLException, url:xxx, errorCode 0, state 08S01The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
【原始代码】:
public static void getDataSource(DataConfig dataConfig) throws Exception{try {Properties properties = new Properties();properties.setProperty("driverClassName",dataConfig.getDriverClassName());properties.setProperty("url",dataConfig.getUrl());properties.setProperty("username",dataConfig.getUserName());properties.setProperty("password",dataConfig.getPassWord());DataSource ds = DruidDataSourceFactory.createDataSource(properties);} catch (Exception e) {e.printStackTrace();}}
解决办法
【参数说明】
【修改后的代码】
public static void getDataSource(DataConfig dataConfig) throws Exception{try {Properties properties = new Properties();properties.setProperty("driverClassName",dataConfig.getDriverClassName());properties.setProperty("url",dataConfig.getUrl());properties.setProperty("username",dataConfig.getUserName());properties.setProperty("password",dataConfig.getPassWord());properties.setProperty("maxWait","500");//如果失败,当前的请求可以返回DruidDataSource druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);druidDataSource.setConnectionErrorRetryAttempts(0);// 失败后重连的次数druidDataSource.setBreakAfterAcquireFailure(true);//请求失败之后中断DataSource ds = druidDataSource;//如果有需要使用javax.sql.DataSource的话} catch (Exception e) {e.printStackTrace();}}
踩坑总结
不要在properties中配置connectionErrorRetryAttempts和breakAfterAcquireFailure,没有效果
连接失败的具体错误信息,catch不到,源码中已经catch了异常信息,做了相关处理
到此这篇关于解决Druid动态数据源配置重复刷错误日志的问题的文章就介绍到这了,更多相关Druid动态数据源配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
并且如此真实的活着——这,就是旅行的意义。