栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MySQL 集群 (五) --------- 多数据源问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MySQL 集群 (五) --------- 多数据源问题

目录
  • 一、概述
  • 二、常见的多数据源技术选型模式
  • 三、Spring + Mybatis 方案一实现步骤
  • 四、Spring + Mybatis 方案一加事务管理
  • 五、Spring + MyBatis 方案二实现步骤
  • 六、Spring + Mybatis 方案二加事务管理
  • 七、SpringBoot + Mybatis 方案一实现步骤
  • 八、SpringBoot + Mybatis 方案一加事务管理
  • 九、SpringBoot + Mybatis 方案二实现步骤
  • 十、SpringBoot + Mybatis 方案二加事务管理


一、概述

多数据源问题是指在一个项目工程中,需要连接多个数据库。前几篇文章我们配置了数据库的主从,在实际开发中可能会有以下几种情况。

① 读写分离 : 项目中使用多数据源
② 项目中只操作主库 (读和写),从库只是起到了备份作用,程序员不需要关心主从结构

二、常见的多数据源技术选型模式

① JDBC
项目是JDBC开发,比较老。编写多个 getConnection 方法,分别连接不同的数据库即可

② Hibernate
项目是 SSH 框架开发,现在项目使用少一些
Spring + Hibernate
Springboot + Hibernate

③ Mybatis
项目是 SSM 框架开发
Spring + Mybatis
Springboot + Mybatis
Spring + JPA
Springboot + JPA

我们这里主要给大家介绍 Spring+Mybatis 和 SpringBoot+Mybatis 开发模式下的多数据源问题。

三、Spring + Mybatis 方案一实现步骤

核心思想 :基于 Mapper 包的隔离,每个 Mapper 包操作不同的数据库,每个 Mapper 包对应一个数据库

A、创建一个普通的 maven 项目

创建 maven 项目名为 :multi-datasource-spring


B、在 pom.xml 文件中添加相关的依赖



    org.springframework
    spring-jdbc
    5.1.4.RELEASE


    org.springframework
    spring-tx
    5.1.4.RELEASE


    org.springframework
    spring-context
    5.1.4.RELEASE




    org.mybatis
    mybatis
    3.4.6



    org.mybatis
    mybatis-spring
    1.3.2



    mysql
    mysql-connector-java
    5.1.43



    com.alibaba
    druid
    1.1.1

C、在 pom.xml 文件添加 resource,指定编译 MyBatis 映射文件


    
        
            src/main/java
            
                **
    public static void setDataSourceKey(String dataSourceKey){
        holder.set(dataSourceKey);
    }

    
    public static String getDataSourceKey(){
        return holder.get();
    }
}

(7) 对 DynamicDataSource 类中的方法进行实现

protected Object determineCurrentLookupKey() {
    //在操作数据库前要确定是哪个数据源的key返回
    return ThreadLocalHolder.getDataSourceKey();
}

C、在 applicationContext-mybatis.xml 配置 Mapper 包扫描器,直接扫描mapper 包即可


    
    

之后进行测试即可

六、Spring + Mybatis 方案二加事务管理

A、在 applicationContext-mybatis.xml 添加事务管理器

并开启事务注解

如果只有一个事务管理器,那么开启事务注解的时候,transaction-manager 属性可以省略



    


B、修改 UserServiceImpl 更新用户方法上加的事务注解

@Transactional
public int updateUserFrom3307(User user) {
    int updateRow = userMapper3307.updateByPrimaryKeySelective(user);
    System.out.println(updateRow);
    int a = 10/0;
    return updateRow;
}
@Transactional
public int updateUserFrom3308(User user) {
    int updateRow = userMapper3308.updateByPrimaryKeySelective(user);
    System.out.println(updateRow);
    int a = 10/0;
    return updateRow;
}
@Transactional
public int updateUserFrom3309(User user) {
    int updateRow = userMapper3309.updateByPrimaryKeySelective(user);
    System.out.println(updateRow);
    int a = 10/0;
    return updateRow;
}
@Transactional
public int updateUserFrom3310(User user) {
    int updateRow = userMapper3310.updateByPrimaryKeySelective(user);
    System.out.println(updateRow);
    int a = 10/0;
    return updateRow;
}

C、在 Test 类进行测试

进行数据库操作前,需要先指定数据源

七、SpringBoot + Mybatis 方案一实现步骤

核心思想:基于 Mapper 包的隔离,每个 Mapper 包操作不同的数据库,每个 Mapper 包对应一个数据库

A、创建一个 SpringBoot 的 java 项目

名为 multi-datasource-springboot


不需要添加任何依赖就普通 Java 工程即可

C、在 pom.xml 文件中添加 MyBatis 的依赖



   org.mybatis.spring.boot
   mybatis-spring-boot-starter
   
   1.3.2




   mysql
   
   mysql-connector-java




   com.alibaba
   druid
   1.1.1

D、在 pom.xml 文件中指定 resource,对 MyBatis 映射文件编译


	
		src/main/java
		
			**
    @Bean//相当于xml中的bean
    public DruidDataSource dataSource3307(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceConfigInfo.getUrl3307());
        druidDataSource.setDriverClassName(dataSourceConfigInfo.getDriver3307());
        druidDataSource.setUsername(dataSourceConfigInfo.getUsername3307());
        druidDataSource.setPassword(dataSourceConfigInfo.getPassword3307());
        return druidDataSource;
    }

    
    @Bean
    public SqlSessionFactoryBean sessionFactory3307(){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource3307());
        return sqlSessionFactoryBean;
    }

    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate3307() throws Exception{
        //sessionFactory3307()方法返回SqlSessionFactoryBean,需要调用getObject返回SqlSessionFactory
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sessionFactory3307().getObject());
        return sqlSessionTemplate;
    }
}

复制 MyDataSource3307 类为 3308|3309|3310 ,并改变类中的内容为对应的数据源编号

I、从 multi-datasource-spring 中拷贝 model、service 到当前 multi-datasource-springboot 中

J、在 Application 中添加测试代码进行测试

@SpringBootApplication
public class Application {
   public static void main(String[] args) {
      ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
      UserService userService = context.getBean("userServiceImpl",UserService.class);
        System.out.println("3307数据库:" +userService.getUserByIdFrom3307(4).getName());
        System.out.println("3308数据库:" +userService.getUserByIdFrom3308(3).getName());
        System.out.println("3309数据库:" +userService.getUserByIdFrom3309(4).getName());
        System.out.println("3310数据库:" +userService.getUserByIdFrom3310(4).getName());
   }
}
八、SpringBoot + Mybatis 方案一加事务管理

A、在 MyDataSource3307 类中添加对事物的处理

@Bean("transactionManager3307")
public DataSourceTransactionManager transactionManager3307(){
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    dataSourceTransactionManager.setDataSource(dataSource3307());
    return dataSourceTransactionManager;
}

B、在 MyDataSource3308|3309|3310 类中同样添加对事物的处理

C、在 UserServiceImpl 实现类中需要控制事务的方法上添加事务注解

例如

D、在 Application 类中编写代码测试

User user = new User();
user.setId(3);
user.setName("boot-3309123");
userService.updateUserFrom3309(user);
九、SpringBoot + Mybatis 方案二实现步骤

核心思想:基于动态数据源,在运行的时候才知道要是用哪个数据源

A、将 Spring + Mybatis 方案二实现中的 applicationContext -mybatis.xml 配置信息用 SpringBoot 注解替换

因为方案二是基于动态数据源的,所以先将我们前面multi-datasource-spring 中定义的动态数据源DynamicDataSource 类以及 ThreadLocal 类拷贝到 multi-datasource-springboot 中


在 com.fancy.multi.config 下创建 MyDataSource 类

@Configuration //相当于一个xml文件
@MapperScan(basePackages="com.fancy.multi.mapper",sqlSessionTemplateRef = "sqlSessionTemplate")
public class MyDataSource {
    @Autowired//注入我们自定义属性的映射类
    private DataSourceConfigInfo dataSourceConfigInfo;

    
    @Bean//相当于xml中的bean
    public DruidDataSource dataSource3307(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceConfigInfo.getUrl3307());
        druidDataSource.setDriverClassName(dataSourceConfigInfo.getDriver3307());
        druidDataSource.setUsername(dataSourceConfigInfo.getUsername3307());
        druidDataSource.setPassword(dataSourceConfigInfo.getPassword3307());
        return druidDataSource;
    }
    
    @Bean//相当于xml中的bean
    public DruidDataSource dataSource3308(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceConfigInfo.getUrl3308());
        druidDataSource.setDriverClassName(dataSourceConfigInfo.getDriver3308());
        druidDataSource.setUsername(dataSourceConfigInfo.getUsername3308());
        druidDataSource.setPassword(dataSourceConfigInfo.getPassword3308());
        return druidDataSource;
    }
    
    @Bean//相当于xml中的bean
    public DruidDataSource dataSource3309(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceConfigInfo.getUrl3309());
        druidDataSource.setDriverClassName(dataSourceConfigInfo.getDriver3309());
        druidDataSource.setUsername(dataSourceConfigInfo.getUsername3309());
        druidDataSource.setPassword(dataSourceConfigInfo.getPassword3309());
        return druidDataSource;
    }
    
    @Bean//相当于xml中的bean
    public DruidDataSource dataSource3310(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(dataSourceConfigInfo.getUrl3310());
        druidDataSource.setDriverClassName(dataSourceConfigInfo.getDriver3310());
        druidDataSource.setUsername(dataSourceConfigInfo.getUsername3310());
        druidDataSource.setPassword(dataSourceConfigInfo.getPassword3310());
        return druidDataSource;
    }
    
    @Bean
    public SqlSessionFactoryBean sessionFactory(){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        return sqlSessionFactoryBean;
    }
    
    @Bean
    public DynamicDataSource dynamicDataSource(){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map targetDataSources = new ConcurrentHashMap();
        targetDataSources.put(DynamicDataSource.DATASOURCE_KEY_3307,dataSource3307());
        targetDataSources.put(DynamicDataSource.DATASOURCE_KEY_3308,dataSource3308());
        targetDataSources.put(DynamicDataSource.DATASOURCE_KEY_3309,dataSource3309());
        targetDataSources.put(DynamicDataSource.DATASOURCE_KEY_3310,dataSource3310());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        return dynamicDataSource;
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate() throws Exception{
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sessionFactory().getObject());
        return sqlSessionTemplate;
    }
}

之后测试同样根据上面的步骤来即可。

十、SpringBoot + Mybatis 方案二加事务管理

A、在 MyDataSource 类中添加如下配置

@Bean
public DataSourceTransactionManager transactionManager(){
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    dataSourceTransactionManager.setDataSource(dynamicDataSource());
    return dataSourceTransactionManager;
}

B、在 Application 类上添加事务注解驱动,并测试

注意:操作数据库前需要指定数据源

@SpringBootApplication
@EnableTransactionManagement
public class Application {
   public static void main(String[] args) {
      ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
      UserService userService = context.getBean("userServiceImpl",UserService.class);
      User user = new User();
      user.setId(3);
      user.setName("boot-123");
      ThreadLocalHolder.setDataSourceKey(DynamicDataSource.DATASOURCE_KEY_3309);
      userService.updateUserFrom3309(user);
   }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929698.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号