SSM框架、Druid连接池实现多数据源配置(已上线使用)


总体大概流程:

  1、配置数据源、账密(账密一致,文章不多阐述)

  driverClassName = com.mysql.jdbc.Driver
  validationQuery = SELECT 1 FROM DUAL

# 腕表
jdbc_url = jdbc:mysql://127.0.0.1:3306/do_wave_new?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

# 车机
jdbc_url2 = jdbc:mysql://127.0.0.1:3306/car_internet?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

jdbc_username = root
jdbc_password = dowave!@#888
jdbc_initialSize = 2 jdbc_minIdle = 1 jdbc_maxActive = 500 jdbc_maxWait = 1800000

  2、Mybytis.xml 配置数据源

   
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}" /> 
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        
        <property name="initialSize" value="${jdbc_initialSize}" />
        
        <property name="maxActive" value="${jdbc_maxActive}" />
        
        <property name="minIdle" value="${jdbc_minIdle}" />
        
        <property name="maxWait" value="${jdbc_maxWait}" />

        
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="300000" />

        
        <property name="removeAbandoned" value="true" />
        
        <property name="removeAbandonedTimeout" value="1800" />
        
        <property name="logAbandoned" value="true" />

        
        
        <property name="filters" value="stat" />
        
        
        <property name="useUnfairLock" value="true" />
    bean>
    
    
    <bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
          <property name="driverClassName" value="${driverClassName}" /> 
        <property name="url" value="${jdbc_url2}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        
        <property name="initialSize" value="${jdbc_initialSize}" />
        
        <property name="maxActive" value="${jdbc_maxActive}" />
        
        <property name="minIdle" value="${jdbc_minIdle}" />
        
        <property name="maxWait" value="${jdbc_maxWait}" />

        
        <property name="poolPreparedStatements" value="true" /> 
        <property name="maxPoolPreparedStatementPerConnectionSize" value="33" />

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="300000" />

        
        <property name="removeAbandoned" value="true" />
        
        <property name="removeAbandonedTimeout" value="1800" />
        
        <property name="logAbandoned" value="true" />

        
        
        <property name="filters" value="stat" />
        
        
        <property name="useUnfairLock" value="true" />
    bean>
    
    <bean id="dynamicDataSource" class="com.dowave.datasource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                
                <entry key="ds1" value-ref="dataSource"/>
                
                <entry key="ds2" value-ref="dataSource2"/>
            map>
        property>
        
        <property name="defaultTargetDataSource" ref="dataSource"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dynamicDataSource" />
        
        <property name="mapperLocations" value="classpath:com/XXXXXX/entity/mapper/*.xml" />
    bean>

  3、数据源切换工具类

    枚举类:代表对应的数据源

public enum DataSourceEnum {

    DS1("ds1"), DS2("ds2");

    private String key;

    DataSourceEnum(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

    创建创建 DynamicDataHolder 用于持有当前线程中使用的数据源标识

public class DataSourceHolder {
    private static final ThreadLocal dataSources = new ThreadLocal();

    public static void setDataSources(String dataSource) {
        dataSources.set(dataSource);
    }

    public static String getDataSources() {
        return dataSources.get();
    }
}

    创建DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法

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

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSources();
    }

}

  4、自动切换数据源,利用AOP,进行自动切换数据源
创建切面类 DataSourceExchange,切面的规则可以自定义,根据自己的项目做自己的规则,我这边用 citn 表示不同的数据源。

public class DataSourceExchange {

    public void before(JoinPoint point) {

        // 获取目标对象的类类型
        Class<?> aClass = point.getTarget().getClass();
        String c = aClass.getName();
        String[] s = c.split("\\.");
        // 获取包名用于区分不同数据源
        String packageName = s[3];

        if ("citn".equals(packageName)) {
            DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
            System.out.println("数据源:" + DataSourceEnum.DS2.getKey());
        } else {
            DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
            System.out.println("数据源:" + DataSourceEnum.DS1.getKey());
        }
    }

    /**
     * 执行后将数据源置为默认
     */
    public void after() {
        DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
    }

}

  5、Spring.xml 配置AOP切面,expression 为切入点,根据自己项目调整。

   class="com.dowave.datasource.DataSourceExchange" />
    
    
        
            
            
            
        
    

  6、需要使用其他数据源在 *ServiceImpl 的位置切换数据源即可

@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private AgentDao agentDao;
    @Autowired
    private AdminAgentDao adminAgentDao;

    @Override
    public Admin login(AdminForm form) {
        DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
        return adminDao.login(form);
    }
}

附:结构目录