druid动态数据源配置 主要是继承abstractroutingdatasource再通过aop来实现动态数据源切换.

下面给大家介绍druid动态配置数据源重复刷错误日志问题,具体内容如下所示:

问题描述

功能需求
使用druid数据库连接池实现 动态的配置数据源功能:ip、端口、用户名、密码都是用户页面手动输入,可以测试连接,保存数据源。

问题说明:
既然是用户自己配置的数据源,就无法避免输入错误,连接失败等情况。

预期情况:用户输入的配置错误,测试连接时,会返回连接失败的信息。

实际情况:数据源测试连接,连接失败后:

后台一直打印错误信息,一直自动重连

方法被阻塞无返回信息,导致前端页面一直处于等待状态

【错误信息】:

com.alibaba.druid.pool.druiddatasource-create connection sqlexception, , errorcode 0, state 08s01
the 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();
	}
}

解决办法

【参数说明】

参数 解释
connectionerrorretryattempts 连接出错后再尝试连接次数
breakafteracquirefailure 数据库服务宕机自动重连机制
maxwait 超时等待时间

【 修改后的代码】

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了异常信息,做了相关处理