hikari如何切换数据源_基于HikariCP连接池实现的多数据源动态切换

packagecom.wanda.crs.common.core;importjava.io.IOException;importjava.util.HashMap;importjava.util.Iterator;importjava.util.LinkedHashMap;importjava.util.List;importjava.util.Map;importorg.springframework.beans.BeansException;importorg.springframework.beans.factory.support.BeanDefinitionBuilder;importorg.springframework.beans.factory.support.DefaultListableBeanFactory;importorg.springframework.context.ApplicationContext;importorg.springframework.context.ApplicationContextAware;importorg.springframework.context.ApplicationEvent;importorg.springframework.context.ApplicationListener;importorg.springframework.context.ConfigurableApplicationContext;importorg.springframework.context.event.ContextRefreshedEvent;importorg.springframework.jdbc.core.JdbcTemplate;importcom.wanda.crs.common.entity.DbConfig;importcom.wanda.crs.utils.PropertyUtil;public class DynamicCreateDataSourceBean implementsApplicationContextAware,

ApplicationListener{private static final String DBFILE_PATH = "/jdbc.properties";privateConfigurableApplicationContext app;privateJdbcTemplate jdbcTemplate;privateDynamicDataSource dataSource;public voidsetJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate =jdbcTemplate;

}public voidsetDataSource(DynamicDataSource dataSource) {this.dataSource =dataSource;

}

@Overridepublic voidsetApplicationContext(ApplicationContext app)throwsBeansException {this.app =(ConfigurableApplicationContext)app;

}

@Overridepublic voidonApplicationEvent(ApplicationEvent event) {//如果是容器刷新事件OR Start Event

if (event instanceofContextRefreshedEvent) {try{

regDynamicBean();

}catch(IOException e) {

e.printStackTrace();

}//System.out.println(event.getClass().getSimpleName()+" 事件已发生!");

}

}private void regDynamicBean() throwsIOException {//解析属性文件,得到数据源Map

Map mapCustom =parsePropertiesFile();//把数据源bean注册到容器中

addSourceBeanToApp(mapCustom);

}/*** 功能说明:根据DataSource创建bean并注册到容器中

*

*@paramacf

*@parammapCustom*/

private void addSourceBeanToApp(MapmapCustom) {

DefaultListableBeanFactory acf=(DefaultListableBeanFactory) app.getAutowireCapableBeanFactory();

PropertyUtil propertyUtil= newPropertyUtil();

String readOnly= propertyUtil.getProperty(DBFILE_PATH, "readOnly");

String connectionTimeout= propertyUtil.getProperty(DBFILE_PATH, "connectionTimeout");

String idleTimeout= propertyUtil.getProperty(DBFILE_PATH, "idleTimeout");

String maxLifetime= propertyUtil.getProperty(DBFILE_PATH, "maxLifetime");

String maximumPoolSize= propertyUtil.getProperty(DBFILE_PATH, "maximumPoolSize");

String connectionTestQuery= propertyUtil.getProperty(DBFILE_PATH, "connectionTestQuery");

String DATASOURCE_BEAN_CLASS= "com.zaxxer.hikari.HikariDataSource";

BeanDefinitionBuilder bdb;

Iterator iter =mapCustom.keySet().iterator();

Map targetDataSources = new LinkedHashMap();//BeanDefinition beanDefinition = new ChildBeanDefinition("portal");//将默认数据源放入 targetDataSources map中

targetDataSources.put("portal1", app.getBean("portal"));//根据数据源得到数据,动态创建数据源bean 并将bean注册到applicationContext中去

while(iter.hasNext()) {//bean ID

String beanKey =iter.next();//创建bean

bdb =BeanDefinitionBuilder.rootBeanDefinition(DATASOURCE_BEAN_CLASS);

bdb.getBeanDefinition().setAttribute("id", beanKey);

bdb.getBeanDefinition().setAttribute("destroy-method", "close");

bdb.addPropertyValue("driverClassName", mapCustom.get(beanKey).getDriverclass());

bdb.addPropertyValue("jdbcUrl", mapCustom.get(beanKey).getJdbcurl());

bdb.addPropertyValue("username", mapCustom.get(beanKey).getUsername());

bdb.addPropertyValue("password", mapCustom.get(beanKey).getPassword());

bdb.addPropertyValue("readOnly", readOnly);

bdb.addPropertyValue("connectionTimeout", Integer.parseInt(connectionTimeout));

bdb.addPropertyValue("idleTimeout", Integer.parseInt(idleTimeout));

bdb.addPropertyValue("maxLifetime", Integer.parseInt(maxLifetime));

bdb.addPropertyValue("maximumPoolSize", Integer.parseInt(maximumPoolSize));

bdb.addPropertyValue("connectionTestQuery", connectionTestQuery);//注册bean

acf.registerBeanDefinition("ds" +beanKey, bdb.getBeanDefinition());//放入map中,注意一定是刚才创建bean对象

targetDataSources.put(beanKey, app.getBean("ds" +beanKey));

}//将创建的map对象set到 targetDataSources;

dataSource.setTargetDataSources(targetDataSources);//必须执行此操作,才会重新初始化AbstractRoutingDataSource 中的//resolvedDataSources,也只有这样,动态切换才会起效

dataSource.afterPropertiesSet();

}/*** 功能说明:GET ALL SM_STATIONS FROM DB1

*

*@return*@throwsIOException*/@SuppressWarnings("rawtypes")private MapparsePropertiesFile()throwsIOException {

String sql= "SELECT ID_COMPANY,DRIVERCLASS,JDBCURL,USERNAME,PASSWORD FROM CRS_DB_CONFIG WHERE IS_DEL=0 AND IS_ENABLED=10091020";

List list=jdbcTemplate.queryForList(sql);

Iterator iterator=list.iterator();

Map mds = new HashMap();while(iterator.hasNext()) {

Map map4station=(Map) iterator.next();

DbConfig dsi= newDbConfig();

dsi.setIdCompany((String)map4station.get("ID_COMPANY"));

dsi.setDriverclass((String)map4station.get("DRIVERCLASS"));

dsi.setJdbcurl((String)map4station.get("JDBCURL"));

dsi.setUsername((String)map4station.get("USERNAME"));

dsi.setPassword((String)map4station.get("PASSWORD"));

mds.put(dsi.getIdCompany(), dsi);

}returnmds;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值