SSM项目多数据源配置

  1. 配置数据源地址、账号、密码
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url1=jdbc:mysql://ip1:3306/easywork?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username1=xxx
jdbc.password1=xxx!

jdbc.url2=jdbc:mysql://ip2:3306/easywork?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username2=xxx
jdbc.password2=xxx

druid.pool.size.max=20
druid.pool.size.min=3
druid.pool.size.init=3
  1. xml中配置数据源
<!--配置整合mybatis过程-->
    
    <!--1、配置数据库相关参数-->
    <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

    <!--2、 数据源druid -->
    <!-- 数据源1 start -->
    <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url1}"/>
        <property name="username" value="${jdbc.username1}"/>
        <property name="password" value="${jdbc.password1}"/>

        <!-- 设置初始大小、最小、最大 连接数-->
        <property name="initialSize" value="${druid.pool.size.init}"/>
        <property name="minIdle" value="${druid.pool.size.min}"/>
        <property name="maxActive" value="${druid.pool.size.max}"/>
        <!-- 配置监控统计拦截的filters,wall用于防止sql注入,stat用于统计分析 -->
        <property name="filters" value="wall,stat" />
    </bean>
    <!-- 数据源1 end -->

    <!-- 数据源2 start -->
    <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url2}"/>
        <property name="username" value="${jdbc.username2}"/>
        <property name="password" value="${jdbc.password2}"/>

        <!-- 设置初始大小、最小、最大 连接数-->
        <property name="initialSize" value="${druid.pool.size.init}"/>
        <property name="minIdle" value="${druid.pool.size.min}"/>
        <property name="maxActive" value="${druid.pool.size.max}"/>
        <!-- 配置监控统计拦截的filters,wall用于防止sql注入,stat用于统计分析 -->
        <property name="filters" value="wall,stat" />
    </bean>
    <!-- 数据源2 end -->
    <bean id="dynamicDataSource" class="com.gs.dataSource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="ds1" value-ref="dataSource1"/>
                <entry key="ds2" value-ref="dataSource2"/>
            </map>
        </property>
        <!--默认数据源-->
        <property name="defaultTargetDataSource" ref="dataSource2"/>
    </bean>

    <!--3、 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dynamicDataSource"/>
        <!-- 配置mybatis全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!-- 扫描entitys包,使用别名;隔开 -->
        <!-- TODO 不能使用通配    但是可以直接指定到  com.trjn.lowsmanage 试了一下 加载速度没有影响 -->
        <property name="typeAliasesPackage" value="com.gs"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/**/*.xml"></property>
        <!--  -->
        <!--  -->
    </bean>

    <!--4、配置扫描Dao接口包,动态实现DAO接口,注入到spring容器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描的Dao接口-->
        <property name="basePackage" value="com.gs.**.dao"/>
    </bean>
  1. 数据源切换工具类
    枚举类
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; }
}

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

/**
 * DynamicDataSourceHolder用于持有当前线程中使用的数据源标识
 */
public class DataSourceHolder {

    private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();

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

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

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

/**
 * DynamicDataSource的类,继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSources();
    }
}
  1. 手动切换数据源
    到这一步,已经可以试用各个数据源了,只需要在Service中查询前,调用一下即可
//teacherService
@Override
public TeacherVO getVOById(Integer id) {
    DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
    return teacherDao.getVOById(id);
}


//productService
@Override
public Product getPOById(Integer id) {
    DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
    return productDao.getPOById(id);
}

此时,两个方法分别从不同的数据源中查询数据

  1. 自动切换数据源
    虽然可以手动切换数据源,但每个方法都切换太过麻烦,很容易忘记,所以可以利用AOP,进行自动切换数据源
    创建切面类DataSourceExchange,切面的规则可以自定义,根据自己的项目做自己的规则,我这边是demo,所以product、teacher包分别用不同的数据源。
public class DataSourceExchange {

    public void before(JoinPoint point) {

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

        if ("product".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(null);
    }

}

配置切面

<bean id="dataSourceExchange" class="com.gs.aop.DataSourceExchange"/>
<aop:config>
    <aop:aspect ref="dataSourceExchange">
        <aop:pointcut id="dataSourcePointcut" expression="execution(* com.gs.**.service.impl.*ServiceImpl.*(..))"/>
        <aop:before pointcut-ref="dataSourcePointcut" method="before"/>
        <aop:after pointcut-ref="dataSourcePointcut" method="after"/>
    </aop:aspect>
</aop:config>

这样,在调用service方法时就会自动切换数据源了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容