Spring多數(shù)據(jù)源配置(干貨)

1.配置多數(shù)據(jù)源連接信息(jdbc.properties)

  • jdbc.properties
# oracle 連接信息
jdbc.oracle.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.oracle.url=jdbc:oracle:thin:@127.0.0.1:6694/{database}
jdbc.oracle.username={userName}
jdbc.oracle.password={passwork}
# mysql 連接信息
jdbc.mysql.driver=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://127.0.0.1:3306/{database}
jdbc.mysql.username={userName}
jdbc.mysql.password={passwork}

2.配置xml文件(springmvc.xml)

#oracle
<bean id="oracleDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
</bean>
#mysql
<bean id="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.mysql.driver}"/>
        <property name="url" value="${jdbc.mysql.url}"/>
        <property name="username" value="${jdbc.mysql.username}"/>
        <property name="password" value="${jdbc.mysql.password}"/>
</bean>
#自定義動(dòng)態(tài)數(shù)據(jù)源實(shí)體配置
<bean id="dataSource" class="cn.xdf.amoy.datasource.DynamicDataSource"><!--注意: 這里寫選擇數(shù)據(jù)源的類地址 下面跟著給出-->
        <property name="defaultTargetDataSource" ref="oracleDataSource"/><!-- 設(shè)置默認(rèn)為此mySqlDataSource數(shù)據(jù)源-->
        <property name="targetDataSources">
            <map>
                <entry key="oracleDataSource" value-ref="oracleDataSource"/>
                <entry key="mysqlDataSource" value-ref="mysqlDataSource"/>
            </map>
        </property>
    </bean>

3.創(chuàng)建動(dòng)態(tài)數(shù)據(jù)源配置類

package cn.cxqnet.datasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * @author MyIreland
 * @description 動(dòng)態(tài)數(shù)據(jù)源實(shí)體
 * @date 2018/10/19
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

    public static final String ORACLE_DATASOURCE = "oracleDataSource";

    public static final String MY_SQL_DATASOURCE = "mysqlDataSource";

    //本地線程,獲取當(dāng)前正在執(zhí)行的currentThread
    public static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    public static void setCurrentDatasource(String dataSourceType){
        contextHolder.set(dataSourceType);
    }

    public static String getCurrentDatasource(){
        return contextHolder.get();
    }

    public static void clearCurrentDatasource(){
        contextHolder.remove();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getCurrentDatasource();
    }
}

4.創(chuàng)建數(shù)據(jù)源注解

package cn.cxqnet.datasource.annotation;

import java.lang.annotation.*;

/**
 * @author MyIreland
 * @description 動(dòng)態(tài)數(shù)據(jù)源注解
 * @date 2018/10/19
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String value() default "";
}

5.創(chuàng)建動(dòng)態(tài)數(shù)據(jù)源切面(注解方式)

package cn.cxqnet.datasource.aspect;

import cn.cxqnet.datasource.DynamicDataSource;
import cn.cxqnet.datasource.annotation.DataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
 * @author MyIreland
 * @description 動(dòng)態(tài)數(shù)據(jù)源切面
 * @date 2018/10/19
 */
@Aspect
@Component
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Pointcut("@annotation(cn.xdf.amoy.datasource.annotation.DataSource)")
    public void dataSourcePointCut() {
    }
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);
        if(ds == null){
            DynamicDataSource.setCurrentDatasource(DynamicDataSource.ORACLE_DATASOURCE);
            logger.debug("set datasource is {}", DynamicDataSource.ORACLE_DATASOURCE);
        }else {
            DynamicDataSource.setCurrentDatasource(DynamicDataSource.MY_SQL_DATASOURCE);
            logger.debug("set datasource is {}", DynamicDataSource.MY_SQL_DATASOURCE);
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearCurrentDatasource();
            logger.debug("clean datasource");
        }
    }
}

6.使用方式

在serviceImpl的方法里面添加@DataSource注解即可

    @Override
    @DataSource("{數(shù)據(jù)庫(kù)名字}")
    public Object save( CmdbAsset asset ) {
        // 保存設(shè)備時(shí),需要執(zhí)行一步對(duì)設(shè)備進(jìn)行編碼的操作。
        String something = dao.doSomething();
    }

這樣就簡(jiǎn)單的實(shí)現(xiàn)了數(shù)據(jù)源的配置,得到幫助的補(bǔ)充詳細(xì)的點(diǎn)哈,springBoot的配置則將其原理轉(zhuǎn)到Class的配置加上@Configuration,寫上@Bean方法配置相關(guān)參數(shù)即可

最后編輯于
?著作權(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 Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,273評(píng)論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評(píng)論 19 139
  • 1. 簡(jiǎn)介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,246評(píng)論 0 4
  • 大家都有自己的生活了,不應(yīng)該再去打擾的。這是很多人的想法,覺得這是尊重別人生活的一種方式,但是,你有沒有想過,不打...
    錦兮辭閱讀 455評(píng)論 0 0
  • 案主,女,大三學(xué)生。 描述: 天氣很好,有陽(yáng)光,花草,很幸福的畫面有一個(gè)小女孩在拔蘿卜,她還養(yǎng)了奶牛和兔子,還有一...
    愛笑的四葉草閱讀 187評(píng)論 0 0

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