spring動(dòng)態(tài)創(chuàng)建數(shù)據(jù)源、動(dòng)態(tài)切換數(shù)據(jù)源

1、創(chuàng)建動(dòng)態(tài)數(shù)據(jù)源RoutingDataSource


package com.yhbc.datasourceT;

import java.util.HashMap;

import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;

import org.hibernate.SessionFactory;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;

//@Component? 不能有這個(gè)注解 ,xml的bean比他晚生成

public class RoutingDataSource extends AbstractRoutingDataSource? {

private? Map dataSources = new HashMap<>();

//@Autowired

//@Qualifier("dataSource")//根據(jù)xml的id寫

private DruidDataSource defaultTargetDataSource ;//主數(shù)據(jù)源注入

JdbcTemplate jdbcTemplate;

protected SessionFactory sessionFactory;


@Override

protected DataSource determineTargetDataSource() {

// 根據(jù)數(shù)據(jù)庫(kù)選擇方案,拿到要訪問(wèn)的數(shù)據(jù)庫(kù)

? ? ? ? String dataSourceName = (String) determineCurrentLookupKey();

? ? ? ? if(RoutingDataSourceContext.MASTER_DATASOURCE.equals(dataSourceName)) {

? ? ? ? ? ? // 訪問(wèn)默認(rèn)主庫(kù)

? ? ? ? ? ? return defaultTargetDataSource;

? ? ? ? }


? ? ? ? // 根據(jù)數(shù)據(jù)庫(kù)名字,從已創(chuàng)建的數(shù)據(jù)庫(kù)中獲取要訪問(wèn)的數(shù)據(jù)庫(kù)

? ? ? ? return (DataSource) this.dataSources.get(dataSourceName);

}

@Override

? ? protected Object determineCurrentLookupKey() {

? ? System.out.println("---determineCurrentLookupKey-----主數(shù)據(jù)源=="+defaultTargetDataSource);

? ? ? ? String dbName = RoutingDataSourceContext.getDataSourceRoutingKey();

? ? ? ? if (StringUtils.isEmpty(dbName)) {

? ? ? ? return RoutingDataSourceContext.getMainKey();

? ? ? ? }

? ? ? ? if (!dataSources.containsKey(dbName)){

? ? ? ? ? ? createAndSaveDataSource(dbName);

? ? ? ? }

? ? ? ? return dbName;

? ? }

? ? private synchronized void createAndSaveDataSource(String dbName) {

? ? ? ? DruidDataSource dataSource = createDruidDataSource(dbName);

? ? ? ? dataSources.put(dbName, dataSource);

? ? ? ? super.setTargetDataSources(dataSources);

? ? ? ? afterPropertiesSet();

? ? }





? ? /**

? ? * 根據(jù)配置創(chuàng)建DruidDataSource

? ? * @param fanDataSource

? ? * @return

? ? */

? ? public? DruidDataSource createDruidDataSource(String dbName ) {


? ? if(dataSources.containsKey(dbName)){

? ? return (DruidDataSource) dataSources.get(dbName);

? ? }

? ? ? ? DruidDataSource dataSource = new DruidDataSource();

? ? ? ? dataSource.setDriverClassName("com.mysql.jdbc.Driver");

? ? ? ? dataSource.setName(dbName);

? ? ? ? dataSource.setUrl("jdbc:mysql://192.168.1.13:3306/"+dbName+"?useUnicode=true&allowMultiQueries=true&useSSL=false");

? ? ? ? dataSource.setUsername("root");

? ? ? ? dataSource.setPassword("root");

? ? ? ? dataSource.setInitialSize(2);

? ? ? ? // 從池中取得鏈接時(shí)做健康檢查,該做法十分保守

? ? ? ? dataSource.setTestOnBorrow(true);

? ? ? ? // 如果連接空閑超過(guò)1小時(shí)就斷開

? ? ? ? dataSource.setMinEvictableIdleTimeMillis(1 * 60000 * 60);

? ? ? ? // 每十分鐘驗(yàn)證一下連接

? ? ? ? dataSource.setTimeBetweenEvictionRunsMillis(600000);

? ? ? ? // 運(yùn)行ilde鏈接測(cè)試線程,剔除不可用的鏈接

? ? ? ? dataSource.setTestWhileIdle(true);

? ? ? ? dataSource.setMaxWait(-1);

? ? ? ? return dataSource;

? ? }


? ? /*public RoutingDataSource() {

? ? //創(chuàng)建主庫(kù)

? ? ? // createAndSaveDataSource(RoutingDataSourceContext.getMainKey());

? ? ? ? dataSources.put(RoutingDataSourceContext.MASTER_DATASOURCE,defaultTargetDataSource );

? ? ? ? System.out.println("構(gòu)造動(dòng)態(tài)數(shù)據(jù)源,加入主數(shù)據(jù)源=="+defaultTargetDataSource);

? ? ? ? DruidDataSource dataSource = createDruidDataSource();

? ? ? ? jdbcTemplate = new JdbcTemplate();

? ? ? ? jdbcTemplate.setDataSource(dataSource);

? ? ? ? System.out.println("===========testQy========="+testQy());

? }*/



? ? /**

? ? * 通過(guò)jdbc從數(shù)據(jù)庫(kù)中查找數(shù)據(jù)源配置

? ? * @param name

? ? * @return

? ? */

? ? private int testQy() {

? ? ? ? String sql = "select id? from box_function? where url='1-supplyCodeList.htm' ";

? ? ? // RowMapper<FanDataSource> rowMapper = new BeanPropertyRowMapper<>(FanDataSource.class);

? ? ? ? int? id = jdbcTemplate.queryForInt(sql);

? ? ? ? return id;

? ? }



public void setDefaultTargetDataSource(DruidDataSource defaultTargetDataSource) {

System.out.println("---setDefaultTargetDataSource-----主數(shù)據(jù)源=="+defaultTargetDataSource);

this.defaultTargetDataSource = defaultTargetDataSource;

}

}

2、創(chuàng)建線程切換類RoutingDataSourceContext,用來(lái)切換數(shù)據(jù)庫(kù)的名稱

package com.yhbc.datasourceT;

public class RoutingDataSourceContext? {

? ? static final ThreadLocal<String> threadLocalDataSourceKey = new ThreadLocal<>();

? ? public static final String MASTER_DATASOURCE="defaultDataSource";

? ? /**

? ? * 獲取主數(shù)據(jù)庫(kù)的key

? ? * @return

? ? */

? ? public static String getMainKey() {

? ? ? ? return MASTER_DATASOURCE;

? ? }

? ? /**

? ? * 獲取數(shù)據(jù)庫(kù)key

? ? * @return

? ? */

? ? public static String getDataSourceRoutingKey() {

? ? ? ? String key = threadLocalDataSourceKey.get();

? ? ? ? return key == null ? getMainKey() : key;

? ? }

? ? /**

? ? * 設(shè)置數(shù)據(jù)庫(kù)的key

? ? * @param key

? ? */

? ? public static void setThreadLocalDataSourceKey(String key) {

? ? ? ? threadLocalDataSourceKey.set(key);

? ? }

}


3、關(guān)鍵的一步,數(shù)據(jù)源關(guān)聯(lián)session

仔細(xì)觀察哦,routingDataSource在bean中,賦予sessionFactory

<beans:bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">

<beans:property name="driverClassName" value="${silverbox.driver}" />

<beans:property name="url" value="${silverbox.url}" />

<beans:property name="username" value="${silverbox.username}" />

<beans:property name="password" value="${silverbox.password}" />

<beans:property name="maxActive" value="${silverbox.maxActive}" />

<beans:property name="validationQuery" value="${silverbox.testSql}"/>

<beans:property name="testWhileIdle" value="true"/>

<beans:property name="initialSize" value="${silverbox.initialSize}"/>

<beans:property name="maxWait" value="${silverbox.maxWait}"/>

</beans:bean>

<beans:bean id="routingDataSource" class="com.yhbc.datasourceT.RoutingDataSource">

<beans:property name="targetDataSources">

<beans:map key-type="java.lang.String">

<beans:entry key="defaultDataSource" value-ref="dataSource" />

</beans:map>

</beans:property>

<beans:property name="defaultTargetDataSource" ref="dataSource" ></beans:property>

</beans:bean>

<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<!-- <beans:property name="dataSource" ref="dataSource" /> -->

<beans:property name="dataSource" ref="routingDataSource" />

<beans:property name="packagesToScan">

<beans:list>

<beans:value>com.yhbc.entity</beans:value>

</beans:list>

</beans:property>

<beans:property name="hibernateProperties">

<beans:value>

hibernate.dialect= org.hibernate.dialect.MySQLDialect

hibernate.show_sql=false

hibernate.format_sql=false

hibernate.query.substitutions=true 1, false 0

hibernate.jdbc.batch_size=20

hibernate.cache.use_query_cache=false

hibernate.cache.use_second_level_cache=true

hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory

hibernate.search.default.directory_provider=filesystem

hibernate.search.default.indexBase=d:\\index

</beans:value>

</beans:property>

</beans:bean>


4、測(cè)試,接下來(lái)在control中切換調(diào)用:

@RequestMapping(value = { "/hybd-findfunction.htm" }, produces = "text/html;charset=UTF-8")

? ? @ResponseBody

? ? public String findfunction(String functionUsername,String dbtype) {

? ? JSONObject jo=new JSONObject();

? ? log.info("-----------------------------/hybd-add.htm");

? ? ? ? try {

? ? ? ? //silverbox_backup

? ? ? ? /*Dbs.setDbType("backup");

? ? ? ? dynamicDataSource.determineTargetDataSource();*/

? ? ? ? if(dbtype!=null){

? ? ? ? //切換數(shù)據(jù)源,dbtype是數(shù)據(jù)庫(kù)名稱哦,這里的所有數(shù)據(jù)源默認(rèn)都是相同的host,只是庫(kù)的區(qū)別

? ? ? ? RoutingDataSourceContext.setThreadLocalDataSourceKey(dbtype);

? ? ? ? }


? ? System.out.println("sessionFactory==="+sessionFactory.toString());


? ? ? ? List<?> list=this.hYBDService.findFunction(functionUsername);


? ? ? ? jo.put("msg", "添加成功");

? ? ? ? jo.put("list", list);

? ? ? ? jo.put("success", true);

? ? ? ? } catch (Exception e) {

? ? ? ? jo.put("success", false);

? ? ? ? ? e.printStackTrace();

? ? ? ? ? log.error("error---hybd-add.htm-----:"+Utils.log4jDetail(e));

? ? ? ? }

? ? ? ? return jo.toJSONString();

? ? }

親測(cè)通過(guò)哦,如果有用請(qǐng)多多支持哦

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,568評(píng)論 19 139
  • ?著作權(quán)歸作者所有:來(lái)自51CTO博客作者優(yōu)秀android的原創(chuàng)作品,如需轉(zhuǎn)載,請(qǐng)注明出處,否則將追究法律責(zé)任 ...
    傳奇內(nèi)服號(hào)閱讀 1,202評(píng)論 0 9
  • 上一章:墨白淵淺|三生三世桃花依舊 2 天宮 洗梧宮裝飾著紅色的綢帶,連往日的燭臺(tái)和燈籠都換成了大紅色,夜華不喜,...
    夏汐baby閱讀 13,948評(píng)論 4 40
  • 錯(cuò)誤堆棧如下 hashMap的相關(guān)實(shí)現(xiàn)源碼如下: 顯然,工程中使用了迭代器遍歷hashMap時(shí)并且map的size...
    JeniusYang閱讀 6,381評(píng)論 0 0
  • 我是文科女生,出來(lái)工作已近十年。一貫的思維習(xí)慣都是典型文科犯----委婉含蓄。此前并沒覺得有什么不好,直到家人從去...
    摩登主婦閱讀 145評(píng)論 0 0

友情鏈接更多精彩內(nèi)容