前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在SSM项目中扩展配置多数据源

在SSM项目中扩展配置多数据源

作者头像
鳄鱼儿
发布2024-05-22 08:53:24
740
发布2024-05-22 08:53:24
举报

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情

一个ssm项目中需要扩展多个数据源,原来只有一个mysql,现在需要再扩展一个mysql,现将需要改动的地方做一个记录。

db.properties修改

首先,需要在数据源配置文件中增加新数据源配置。因为都是mysql,除了需要改动的,其他配置都是用了一样的参数,如果需要更改,可以自行增加配置参数。

代码语言:javascript
复制
# 数据源1
jdbc.user=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
​
# 数据源2
jdbc2.jdbcUrl=jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
jdbc2.user=root
jdbc2.password=root
​
# 公用配置
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.initPoolSize=5
jdbc.maxPoolSize=1024

spring.xml修改

spring.xml中需要新增数据源配置,以及多源数据库如何选择的配置。

代码语言:javascript
复制
​
    <!-- 导入资源文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
​
    <!-- db1数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
    <!--    db2数据库-->
    <bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc2.user}"></property>
        <property name="password" value="${jdbc2.password}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc2.jdbcUrl}"></property>
        <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
    </bean>
      
    <!-- 动态选择数据源,指向com.demo.test.dataSource.DynamicDataSource,后文会贴出代码 -->
    <bean id="dynamicDataSource" class="com.demo.test.dataSource.DynamicDataSource">
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="defaultDB" value-ref="dataSource"/>
                <entry key="DataDB" value-ref="dataSource2"/>
            </map>
        </property>
        <!--默认数据源-->
        <property name="defaultTargetDataSource" ref="dataSource2"/>
    </bean>
      
    <!-- 配置 SessionFactory -->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 更改指向 dynamicDataSource -->
        <property name="dataSource" ref="dynamicDataSource"></property>
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>

增加数据源切换类

数据源枚举类

代码语言:javascript
复制
public enum DataSourceEnum {
    DS1("defaultDB"), DS2("DataDB");
    private String key;
​
    DataSourceEnum(String key) {
        this.key = key;
    }
​
    public String getKey() {
        return key;
    }
​
    public void setKey(String key) {
        this.key = key;
    }
}

线程持有数据源标识类

用于标记线程使用哪个数据源标识

代码语言:javascript
复制
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();
    }
}

配置动态数据源类

AbstractRoutingDataSource 类:可以根据用户定义的规则选择当前的数据源,多源数据库需要使用该类实现多源数据库选择。

在每次数据库查询操作前执行,determineCurrentLookupKey() 决定使用哪个数据源。

实现的具体逻辑:继承 AbstractRoutingDataSource 类并重写 determineCurrentLookupKey 方法。把配置的多个数据源会放在AbstractRoutingDataSource的 targetDataSources和defaultTargetDataSource中,然后通过afterPropertiesSet()方法将数据源分别进行复制到resolvedDataSources和resolvedDefaultDataSource中。调用AbstractRoutingDataSource的getConnection()的方法的时候,先调用determineTargetDataSource()方法返回DataSource在进行getConnection()。

代码语言:javascript
复制
public class DynamicDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceHolder.getDataSources();
    }
}

切换数据源代码

配置完上诉代码,到此可以在查询数据源时增加一个选择数据源语句实现选择数据源。例如:

代码语言:javascript
复制
  public User test01(String username) {
    DataSourceHolder.setDataSources(DataSourceEnum.DS1.getKey());
    return userDao.findUserByName(username);
  }
​
  public User test02(String username) {
    DataSourceHolder.setDataSources(DataSourceEnum.DS2.getKey());
    return userDao.findUserByName(username);
  }

自动切换数据源

手动切换数据源需要每个方法都需要进行修改,太过于麻烦。

这里可以利用aop,实现根据包名自动切换数据源。

切面类

db1数据源都在db1包名下,db2数据源都在db2数据源下。如果你的项目文件结构不适用,可以根据能区分开数据源的策略进行自动切换,这个策略需要你自己去想了👻。

代码语言:javascript
复制
​
public class DataSourceExchange {
    public void before(JoinPoint point) {
        //获取目标对象的类类型
        Class<?> aClass = point.getTarget().getClass();
        String c = aClass.getName();
        String[] ss = c.split("\.");
        //获取包名,进行数据源选择。这里根据需求进行修改。
        String packageName = ss[3];
        if ("db2".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为bean的名称,class指向类的位置;aop的execution表示筛选的类,method表示对类使用的方法。

代码语言:javascript
复制
    <!-- DataSourceExchange 注入bean -->
    <bean id="dataSourceExchange" class="com.demo.test.dataSource.DataSourceExchange"/>
    <!-- 配置aop切面 -->
    <aop:config>
        <aop:aspect ref="dataSourceExchange">
        <!-- 限定在哪些包下执行 -->
            <aop:pointcut id="dataSourcePointcut" expression="execution(* com.demo.test..service.impl.*ServiceImpl.*(..))"/>
            <aop:before pointcut-ref="dataSourcePointcut" method="before"/>
            <aop:after pointcut-ref="dataSourcePointcut" method="after"/>
        </aop:aspect>
    </aop:config>

execution语法说明:

比如:* com.demo.test..service.impl.*ServiceImpl.*(..))

第一个 * 表示任意返回值

.. 表示 test 包和它的所有子包

*ServiceImpl 表示任何前缀的ServiceImpl类

最后的*表示,命中类的所有方法

总结

修改配置到这里就已经完成了ssm配置多数据源修改了,如果还出现了报错,请查看错误日志,很可能是配置的参数中指向错误,细心点检查下。

最后的运行结果:

测试完,记得把输出注释掉哦

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • db.properties修改
  • spring.xml修改
  • 增加数据源切换类
    • 数据源枚举类
      • 线程持有数据源标识类
        • 配置动态数据源类
          • 切换数据源代码
          • 自动切换数据源
            • 切面类
              • 在配置中设置切面
              • 总结
              相关产品与服务
              数据库
              云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档