SSM動態配置多數據源

1. 數據源配置 spring.xml

<!-- 配置動態數據源開始 -->
    <!-- 配置鏈接池 druid 數據源,用於訪問mysql數據庫(${}這種寫法稱爲佔位符,具體值在運行時使用db.properties文件中配置的值) com.alibaba.druid.pool.DruidDataSource-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}${jdbc.dbname1}?${jdbc.params}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="validationQuery" value="${validationQuery}"/>
        <property name="poolPreparedStatements" value="${poolPreparedStatements}"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>
        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="stat"/>
    </bean>

    <bean id="dataSourceE" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc.url}${jdbc.dbname2}?${jdbc.params}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="validationQuery" value="${validationQuery}"/>
        <property name="poolPreparedStatements" value="${poolPreparedStatements}"/>
        <property name="maxPoolPreparedStatementPerConnectionSize" value="${maxPoolPreparedStatementPerConnectionSize}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/>
        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="stat"/>
    </bean>

    <!-- 自定義數據源切換類 -->
    <bean id="myDataSource" class="com.zqu.DataSource.DynamicRoutingDataSource">
        <!-- 這裏能夠指定默認的數據源 -->
        <property name="defaultTargetDataSource" ref="dataSource" />
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <!-- 指定lookupKey和與之對應的數據源 -->
                <entry key="dataSource" value-ref="dataSource"></entry>
                <entry key="dataSourceE" value-ref="dataSourceE"></entry>
            </map>
        </property>
    </bean>
    <!-- 配置動態數據源結束 -->

二、配置數據源動態切面 spring.xml

<!-- 數據源動態切換切面配置 -->
    <aop:config>
        <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor" order="1">
            <!-- 攔截全部service實現類的方法 -->
            <aop:pointcut id="dataSourcePointcut"
                          expression="execution(* com.zqu.service..*Impl.*(..))"/>
            <aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
        </aop:aspect>
    </aop:config>

    <!-- 數據源動態切換實體 -->
    <bean id="dataSourceInterceptor" class="com.zqu.DataSource.DynamicDataSourceInterceptor"/>
    <!-- 數據源動態切換切面配置結束 -->

三、配置數據庫鏈接參數 jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/
jdbc.dbname1=family
jdbc.dbname2=employees
jdbc.params= useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123
#配置初始化大小、最小、最大
initialSize=0
maxActive=8
minIdle=0
maxIdle=8

#配置獲取鏈接等待超時的時間
maxWait=20000
validationQuery=select 1

#打開PSCache,而且指定每一個鏈接上PSCache的大小
poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=10

#配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒
timeBetweenEvictionRunsMillis=60000

#配置一個鏈接在池中最小生存的時間,單位是毫秒

minEvictableIdleTimeMillis=1800000

四、定義一個類繼承DynamicRoutingDataSource實現determineCurrentLookupKey方法,來實現數據庫的動態切換

import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;


public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private static final Logger LOG=Logger.getLogger(DynamicRoutingDataSource.class);
    @Override
    protected Object determineCurrentLookupKey() {
        LOG.info("當前數據源:{}"+DynamicDataSourceContextHolder.get());
        return  DynamicDataSourceContextHolder.get();
    }
}

五、定義工具類DynamicDataSourceContextHolder ,用於動態切換數據源

import org.apache.log4j.Logger;

/**
 * @ClassName DynamicDataSourceContextHolder
 * @Description: TODO
 * @Author Jason
 * @Date 2020/3/18  12:15
 * @Version V1.0
 **/
public class DynamicDataSourceContextHolder {
    private  static  final Logger LOG=Logger.getLogger(DynamicDataSourceContextHolder.class);
    private static final ThreadLocal<String> currenDataSource=new ThreadLocal<>();
    /**
     * @Author Jason
     * @Description //清除當前數據源
     * @Date 2020/3/18 12:19
     * @Param
     * @return
     **/
    public static  void clear(){
        currenDataSource.remove();
    }
   /**
    * @Author Jason
    * @Description //Description
    * @Date 2020/3/18 20:50
    * @Param []
    * @return java.lang.String
    **/
    public static String get(){
        return currenDataSource.get();
    }

    /**
     * @Author Jason
     * @Description 設置數據源
     * @Date 2020/3/18 15:49
     * @Param []
     * @return void
     **/
    public static void setDataSource(String datasource) {
        currenDataSource.set(datasource);
    }
}

六、自定義註解@TargetDataSource,經過註解的值來獲取當前數據源,並進行切換

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * @ClassName TargetDataSource
 * @Description: 定義註解
 * @Author Jason
 * @Date 2020/3/18  17:07
 * @Version V1.0
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public  @interface TargetDataSource {
   String value();
}

七、定義攔截器DynamicDataSourceInterceptor,解析註解切換數據源

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;


/**
 * @ClassName DynamicDataSourceInterceptor
 * @Description: 數據源切換攔截器
 * @Author Jason
 * @Date 2020/3/18  17:32
 * @Version V1.0
 **/
public class DynamicDataSourceInterceptor {
    private static final Logger LOG = Logger.getLogger(DynamicDataSourceInterceptor.class);
    /**
     * @Author Jason
     * @Description 攔截目標方法,獲取由@DataSource指定的數據源標識,設置到線程存儲中以便切換數據源
     * @Date 2020/3/18 17:39
     * @Param [point]
     * @return void
     **/
    public void intercept(JoinPoint point) throws Exception {
        Class<?> target = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        resolveDataSource(target, signature.getMethod());
    }

    /**
     * @Author Jason
     * @Description 提取目標對象方法註解和類型註解中的數據源標識
     * @Date 2020/3/18 17:40
     * @Param [clazz, method]
     * @return void
     **/
    private void resolveDataSource(Class<?> clazz, Method method) {
        try {
            Class<?>[] types = method.getParameterTypes();
            // 默認使用類型註解
            if (clazz.isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource source = clazz.getAnnotation(TargetDataSource.class);
                DynamicDataSourceContextHolder.setDataSource(source.value());
            }
            // 方法註解能夠覆蓋類型註解
            Method m = clazz.getMethod(method.getName(), types);
            if (m != null && m.isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource source = m.getAnnotation(TargetDataSource.class);
                DynamicDataSourceContextHolder.setDataSource(source.value());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @Author Jason
     * @Description 執行方法後清除數據源設置
     * @Date 2020/3/18 21:26
     * @Param [joinPoint, targetDataSource]
     * @return void
     **/
    public void afterIntercept(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Class<?>[] types = signature.getParameterTypes();
        Class<?> target = point.getTarget().getClass();
        try {
            Method m = target.getMethod(signature.getName(), types);
            if (m != null && m.isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource source = m.getAnnotation(TargetDataSource.class);
                LOG.info("當前數據源"+ source.value()+ "執行清理方法");
            }
            else{
                LOG.info("當前數據源"+ DynamicDataSourceContextHolder.get()+ "執行清理方法");
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        DynamicDataSourceContextHolder.clear();
    }
}

八、@TargetDataSource註解實現數據源切換實例

import com.zqu.DataSource.TargetDataSource;
import com.zqu.bean.Employees;
import com.zqu.dao.IEmployeesDao;
import com.zqu.service.IEmployeesService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName IEmployeesServiceImpl
 * @Description: TODO
 * @Author Jason
 * @Date 2020/3/18  18:02
 * @Version V1.0
 **/
@Service("employeesService")
public class IEmployeesServiceImpl implements IEmployeesService {
    @Resource(name="IEmployeesDao")
    private IEmployeesDao eDao;
    public List<Employees> findDemo(){
        return eDao.findDemo();
    }
    @TargetDataSource("dataSourceE")//切換數據源dataSourceE
    public List<Employees> find(){
        return  eDao.find();
    }
}

參考文章

相關文章
相關標籤/搜索