ssm框架雙數據源配置

前置條件:大家在開發過程中大多都是連接一個數據庫,進行數據操作,但是在同一個項目工程中,需要連接多個數據庫,進行讀寫操作,這時候就需要配置切換動態數據源。。。,f廢話少說,直接上代碼

這裏已ssm框架爲例,當然項目所需的相關依賴jar都已經集成在框架中了。。。。

1、數據源連接參數

jdbc.properties

#mysql 5.x
jdbc.driver_1=com.mysql.jdbc.Driver
jdbc.url_1=jdbc\:mysql\://127.0.01:3306/db_xedk?autoReconnect\=true&useUnicode\=true&characterEncoding\=utf8&useSSL\=false&failOverReadOnly\=false
jdbc.username_1=root
jdbc.password_1=root

#oracle 11
jdbc.driver_2=oracle.jdbc.driver.OracleDriver
jdbc.url_2=jdbc:oracle:thin:@127.0.01:1521/ORCL
jdbc.username_2=root
jdbc.password_2=root

2、自定義數據源

package com.ssm.core.util;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
 * 動態數據源
 * */
public class DynamicDataSource extends AbstractRoutingDataSource 
{
    @Override
    protected Object determineCurrentLookupKey() {
        return DBContextHolder.getDbType();
    }
 
}

package com.ssm.core.util;

/**
 * 數據源類型
 */
public class DBContextHolder {
    /**
     * 注意:數據源標識保存在線程變量中,避免多線程操作數據源時互相干擾
     */
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    // 設置當前數據源
    public static void setDbType(String dbType) {
        contextHolder.set(dbType);
    }

    // 獲取當前數據源
    public static String getDbType() {
        return ((String) contextHolder.get());
    }

    // 清空上下文數據源
    public static void clearDbType() {
        contextHolder.remove();
    }
}
 

3、配置數據源

spring-dao.xml:

<!-- 配置數據源1 -->
    <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver_1}" />
        <property name="url" value="${jdbc.url_1}" />
        <property name="username" value="${jdbc.username_1}" />
        <property name="password" value="${jdbc.password_1}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置數據源2 -->
    <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver_2}" />
        <property name="url" value="${jdbc.url_2}" />
        <property name="username" value="${jdbc.username_2}" />
        <property name="password" value="${jdbc.password_2}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置SqlSessionFactory,同時指定數據源 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource" />
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="mapperLocations" value="classpath:mybatis/sqlMap/sqlMap*.xml" />
    </bean>
    <!-- 配置掃描包,加載mapper代理對象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.core.*.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

spring-service.xml:

<!-- 配置多數源映射關係 -->
    <bean id="dynamicDataSource" class="com.ssm.core.util.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry value-ref="dataSource1" key="dataSource1"></entry>
                <entry value-ref="dataSource2" key="dataSource2"></entry>
            </map>
        </property>
        <!-- 默認數據源1 -->
        <property name="defaultTargetDataSource" ref="dataSource1"></property>
    </bean>
    
    <!--配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數據源 -->
        <property name="dataSource" ref="dynamicDataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice"
        transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行爲 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS"
                read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS"
                read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS"
                read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 切面-事務管理控制在Service層 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.ssm.core.*.service.*Service.*(..))" />
    </aop:config>
    <context:component-scan
        base-package="com.ssm.core">
        <context:exclude-filter type="regex"
            expression="com.ssm.core.*.*.controller.*" />
    </context:component-scan>

4、使用數據源

使用方式:

 DBContextHolder.setDbType("dataSource1"); //設置數據源
 List<UserInfo> users = userDao.getUserInfoByMap(map); //dao調用

/**
     * 查詢用戶列表_mysql
     */
    public List<UserInfo> getUserListByMysql() 
    {
        Map<String, Object> map = new HashMap<String, Object>();
        //調用mysql數據源 
        DBContextHolder.setDbType("dataSource1");
        List<UserInfo> users = userDao.getUserInfoByMap(map);
        return users;
    }
    
    /**
     * 查詢用戶列表_oracle
     */
    public List<UserEntity> getUserEntityListByOracle() 
    {
        Map<String, Object> map = new HashMap<String, Object>();
        //調用oracle數據源 
        DBContextHolder.setDbType("dataSource2");
        List<UserEntity> users = userDao.getUserEntityByMap(map);
        return users;
    }

5、測試

package com.ssm.core.pc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.ssm.base.BusinessException;
import com.ssm.base.Constant;
import com.ssm.core.pc.entity.UserEntity;
import com.ssm.core.pc.entity.UserInfo;
import com.ssm.core.pc.service.UserInfoService;
import com.ssm.core.util.RedisUtil;
import com.ssm.utils.SmsUtil;
import com.ssm.utils.StringHelper;

@Controller
@RequestMapping(value = "/index")
public class TestController 
{
    
    @Autowired
    private UserInfoService us;

    @RequestMapping(value = "testDynamicDataSource", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> getTest(String type) throws Exception 
    {
        Map<String, Object> rspmap = new HashMap<String, Object>();
        if(StringUtils.isBlank(type)) {
            throw new BusinessException("type不能爲空");
        }
        System.err.println("測試雙數據源start。。。。.");
        List<?> list = new ArrayList<>();
        if("1".equals(type)) {
            System.err.println("調用mysql數據源");
             list = us.getUserListByMysql();
        }
        if("2".equals(type)) {
            System.err.println("調用oracle數據源");
             list = us.getUserEntityListByOracle();            
        }
        rspmap.put("users", list);
        System.err.println("測試雙數據源end。。。。.");
        return rspmap;
    }    

}

調用:http://localhost/ssmDemo/index/testDynamicDataSource.do?type=1

 

以上方法,需要使用哪個就需要設置一下,太過於繁瑣,這個使用切面編程,統一的解決使用哪個數據源。。。。

 實現思路:

a、對於需要使用的dao層,加上自定義的@DataSource("dataSource2")註解

b、使用aop切面,攔截@DataSource註解層,設置對應的數據源

核心代碼:

1、自定義@DataSource註解

package com.ssm.core.util;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
/**自定義@DataSource註解 */
@Target({ ElementType.TYPE,ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME) 
public @interface DataSource {
    String value();
}
 

2、定義DataSourceAspect切面

package com.ssm.base;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
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 com.ssm.core.util.DBContextHolder;
import com.ssm.core.util.DataSource;

/**
 * DataSource切面
 */
@Component
@Aspect
public class DataSourceAspect {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceAspect.class);

    // 指定切入點表單式
    @Pointcut("execution(* com.ssm.core.pc.dao..*.*(..))")
    public void pointCut_() {
    }

    // 前置通知 : 在執行目標方法之前執行
    @Before("pointCut_()")
    public void begin(JoinPoint point) {
        System.err.println("正在設置數據源。。。");
        //獲取由@DataSource指定的數據源標識,設置到線程存儲中以便切換數據源
        Class<?> target = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 默認使用目標類型的註解,如果沒有則使用其實現接口的註解
        for (Class<?> clazz : target.getInterfaces()) {
            resolveDataSource(clazz, signature.getMethod());
        }
        resolveDataSource(target, signature.getMethod());
    
    }

    // 後置/最終通知:在執行目標方法之後執行 【無論是否出現異常最終都會執行】
    @After("pointCut_()")
    public void after(JoinPoint point) {        
        DBContextHolder.clearDbType();
        System.out.println("切換默認數據源成功");
    }

    /**
     * 提取目標對象方法註解和類型註解中的數據源標識
     * 
     * @param clazz
     * @param method
     */
    private void resolveDataSource(Class<?> clazz, Method method) {
        try {
            Class<?>[] types = method.getParameterTypes();
            // 默認使用類型註解
            if (clazz.isAnnotationPresent(DataSource.class)) {
                DataSource source = clazz.getAnnotation(DataSource.class);
                DBContextHolder.setDbType(source.value());
            }
            // 方法註解可以覆蓋類型註解
            Method m = clazz.getMethod(method.getName(), types);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource source = m.getAnnotation(DataSource.class);
                DBContextHolder.setDbType(source.value());

               logger.debug("當前數據源:"+source.value());
            }
        } catch (Exception e) {
            logger.error(clazz + ":" + e.getMessage());
        }
    }
}

在spring-dao.xml,

    <!-- 開啓aop註解方式 -->
    <aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

在對應的dao層使用

@DataSource("dataSource2")
public interface UserEntityDao {
     
    List<UserEntity> getUserEntityByMap(Map<String, Object> map);
}
調用成功,截圖如下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章