Java实战06之idea springboot+mybatis 整合多数据源

目录

一. 前言

二. 数据准备

三、两种模式连接多数据源

1.1 、采用config配置模式,指定数据库操作层的路径实现多数据源

1.2、新增两个config配置

1.3 逻辑层

1.4、启动查看

2、采用dynamic注解的形式添加多数据源

 2.1 pom.xml 新增dynamic 引用

2.2 application.yml 新增多数据源

2.3 逻辑层

2.4启动查看


一. 前言

采用多数据源主要原因是因为最近需要对老项目进行升级改造,特别是数据库方面,老数据库性能跟不上,需要更换性能更好的数据库,然后需要新增数据源,这里采用两种模式。

二. 数据准备

2个数据库,分别命名 dbmysql、dbrich

数据源都新建表

Create Table

CREATE TABLE `studentinfo` (
  `stuId` int(4) NOT NULL DEFAULT '1001',
  `name` varchar(50) NOT NULL DEFAULT '',
  `age` int(4) NOT NULL DEFAULT '10',
  `sex` varchar(10) NOT NULL DEFAULT '男',
  `stuClass` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`stuId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='学生表'

实体类

@Data
public class StudentBo {
    private int stuId;
    private String name;
    private int age;
    private String sex;
    private int stuClass;
}

三、两种模式连接多数据源

1.1 、采用config配置模式,指定数据库操作层的路径实现多数据源

yml 添加多数据源,dbmysql 和 dbrich

spring:
  datasource:
    dbmysql:
      url: jdbc:mysql://XXXX
      username: XXX
      password: XXX
      typ: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 2
      initialSize: 1
      maxWait: 60000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20

    dbrich:
      url: jdbc:mysql://XXXX
      username: XXXX
      password: XXXX
      typ: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 2
      initialSize: 1
      maxWait: 60000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20

1.2、新增两个config配置

数据源 dbmysql配置 

@Configuration
@MapperScan(basePackages = {"com.example.demo.**.mapper"}, sqlSessionFactoryRef = "sqlSessionFactorydbmysql",sqlSessionTemplateRef = "sqlSessionTemplatedbmysql")
public class DatasourcedbmysqlConfiguration {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocation;
    @Value("${spring.datasource.dbmysql.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.dbmysql.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.dbmysql.username}")
    private String username;
    @Value("${spring.datasource.dbmysql.password}")
    private String password;
    @Value("${spring.datasource.dbmysql.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.dbmysql.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.dbmysql.maxActive}")
    private int maxActive;

    @Bean(name = "dbmysql")
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);

        return dataSource;
    }

    @Bean("sqlSessionFactorydbmysql")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dbmysql") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(mapperLocation));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean("sqlSessionTemplatedbmysql")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactorydbmysql") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("transactionManagerdbmysql")
    public DataSourceTransactionManager transactionManager(@Qualifier("dbmysql")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

数据源 dbrich  配置

@Configuration
@MapperScan(basePackages = {"com.example.demo.**.dao"}, sqlSessionFactoryRef = "sqlSessionFactorydbrich")
public class DatasourcedbadbConfiguration {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocation;
    @Value("${spring.datasource.dbrich.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.dbrich.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.dbrich.username}")
    private String username;
    @Value("${spring.datasource.dbrich.password}")
    private String password;
    @Value("${spring.datasource.dbrich.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.dbrich.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.dbrich.maxActive}")
    private int maxActive;

    @Bean(name = "dbrich")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbcUrl);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);

        return dataSource;
    }

    @Bean("sqlSessionFactorydbrich")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dbrich") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(mapperLocation));

        return sqlSessionFactoryBean.getObject();
    }

    @Bean("sqlSessionTemplatedbrich")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactorydbrich") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("transactionManagerdbrich")
    public DataSourceTransactionManager transactionManager(@Qualifier("dbrich")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

 其中数据源 dbmysql 加上了  @Primary ,代表是默认使用的数据源

@MapperScan(basePackages = {"com.example.demo.**.mapper"}

这个注解是指定对应的数据源操作层的路径 ,dbmysql 指定的是mapper 包下的,dbrich 指定的是 dao 包下的

1.3 逻辑层

新建 dao 和mapper 两个包 ,

public interface StudentinfoDao {

    List<StudentBo> selectStudentdbrich();
}
public interface StudentMapper {
    List<StudentBo> selectStudent();

}
@Service
public class StudentService {

    @Resource
    private StudentinfoDao studentinfoDao;

    @Resource
    private StudentMapper studentMapper;

    public List<StudentBo> selectStudentdbrich() {

        return  studentinfoDao.selectStudentdbrich();
    }

    public List<StudentBo> selectStudent() {

        return  studentMapper.selectStudent();
    }


}
@RestController
@RequestMapping("/studentinfoController")
public class StudentinfoController {

    @Autowired
    private StudentService studentService ;

    @RequestMapping("/selectStudent")
    public List<StudentBo> selectStudent(){
        return studentService.selectStudent();
    }

    @RequestMapping("/selectStudentdbrich")
    public List<StudentBo> selectStudentdbrich(){
        return studentService.selectStudentdbrich();
    }

}
@SpringBootApplication
@Import({DatasourcedbadbConfiguration.class, DatasourcedbmysqlConfiguration.class})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

注意:启动类只需要将两个配置类加上不需要添加注解@MapperScan

1.4、启动查看

数据源dbmysql的方法

数据源dbadb的方法

到这里就实现了分包多数据源整合了,下面换另一种方式。

2、采用dynamic注解的形式添加多数据源

 2.1 pom.xml 新增dynamic 引用

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

2.2 application.yml 新增多数据源

# 多数据源
spring:
  datasource:
    dynamic:
      primary: dbmysql #设置默认的数据源或者数据源组,默认值即为master
      strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
      datasource:
        # 主库数据源
        dbmysql:
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.jdbc.Driver
          #本地
          url: jdbc:mysql://XXXX
          username: XXXX
          password: XXXX
        # 从库数据源
        dbadb:
          # 从数据源开关/默认关闭
          enabled: true
          type: com.alibaba.druid.pool.DruidDataSource
          driverClassName: com.mysql.jdbc.Driver
          url: jdbc:mysql://XXXX
          username: XXXXX
          password: XXXXX
    # 初始连接数
    initialSize: 5
    # 最小连接池数量
    minIdle: 10
    # 最大连接池数量
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 300000
    # 配置一个连接在池中最大生存的时间,单位是毫秒
    maxEvictableIdleTimeMillis: 900000
    # 配置检测连接是否有效
    #SELECT 1 FROM DUAL
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    webStatFilter:
      enabled: true
    statViewServlet:
      enabled: true
      # 设置白名单,不填则允许所有访问
      allow:
      url-pattern: #/druid/*
      # 控制台管理用户名和密码
      login-username:
      login-password:
    filter:
      stat:
        enabled: true
        # 慢SQL记录
        log-slow-sql: true
        slow-sql-millis: 1000
        merge-sql: true
      wall:
        config:
          multi-statement-allow: true

2.3 逻辑层

因为是注解的方式,所以启动类需要指定dao层的路径
@SpringBootApplication
@MapperScan(basePackages = {"com.example.demo.**.dao", "com.example.demo.**.mapper"})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

controller、service都一样,不同的是dao

@DS("dbadb")
public interface StudentinfoDao {

    List<StudentBo> selectStudentdbrich();
}
@DS("admysql")
public interface StudentMapper {
    List<StudentBo> selectStudent();

}

这里只需要直接在dao层加上注解DS 配置不同的数据源就可以

默认的数据源可以不需要加注解

2.4启动查看

dbmysql

dbadb

到这里就结束了,可以看出来引用dynamic 注解的方式来加入多数据源会方便很多,不需要额外加配置。

如果觉得对你有帮助的话欢迎点赞关注哦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 首先,为了使用多数据源和分布式事务,我们需要添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency> ``` 接下来,我们需要在application.properties文件中配置数据源和事务管理器: ```properties # 配置主数据源 spring.datasource.url=jdbc:mysql://localhost:3306/main_db?characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 配置从数据源 spring.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?characterEncoding=utf8&useSSL=false spring.datasource.slave.username=root spring.datasource.slave.password=root spring.datasource.slave.driver-class-name=com.mysql.jdbc.Driver # 配置Mybatis mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.entity # 配置Druid数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.initial-size=1 spring.datasource.druid.max-active=10 spring.datasource.druid.min-idle=1 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.filters=stat,wall,log4j spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 配置事务管理器 spring.transaction.default-timeout=600 spring.transaction.rollback-on-commit-failure=true spring.transaction.allow-bean-definition-overriding=true spring.transaction.jta.registry-name=atomikos spring.jta.enabled=true spring.jta.atomikos.connectionfactory.min-pool-size=5 spring.jta.atomikos.connectionfactory.max-pool-size=10 spring.jta.atomikos.connectionfactory.borrow-connection-timeout=30 spring.jta.atomikos.connectionfactory.max-idle-time=60 spring.jta.atomikos.connectionfactory.concurrency-level=100 ``` 然后,我们需要创建两个数据源的配置类,分别为主数据源和从数据源: ```java @Configuration @MapperScan(basePackages = "com.example.mapper.main", sqlSessionTemplateRef = "mainSqlSessionTemplate") public class MainDataSourceConfig { @Bean(name = "mainDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource mainDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "mainSqlSessionFactory") public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/main/*.xml")); return bean.getObject(); } @Bean(name = "mainTransactionManager") public DataSourceTransactionManager mainTransactionManager(@Qualifier("mainDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "mainSqlSessionTemplate") public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` ```java @Configuration @MapperScan(basePackages = "com.example.mapper.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate") public class SlaveDataSourceConfig { @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "slaveSqlSessionFactory") public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml")); return bean.getObject(); } @Bean(name = "slaveTransactionManager") public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "slaveSqlSessionTemplate") public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 最后,我们需要在事务管理器上添加注解@EnableTransactionManagement,并在需要使用事务的方法上添加注解@Transactional: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Transactional(rollbackFor = Exception.class, transactionManager = "mainTransactionManager") @Override public void save(User user) { userMapper.insert(user); } @Transactional(rollbackFor = Exception.class, transactionManager = "slaveTransactionManager") @Override public User findById(int id) { return userMapper.selectByPrimaryKey(id); } } ``` 以上就是使用SpringBoot+Mybatis+druid多数据源和分布式事务的基本步骤。 ### 回答2: Spring Boot是一个用于构建独立的、生产级的应用程序的框架。它简化了应用程序的开发过程,并通过自动配置来减少了繁琐的配置MyBatis是一个ORM(对象关系映射)框架,它提供了将数据库操作映射到Java对象的功能。Druid是一种高性能的数据库连接池。 要在Spring Boot中使用MyBatis和Druid进行多数据源配置和分布式事务管理,可以按照以下步骤进行操作: 1. 添加依赖:在项目的pom.xml文件中,添加Spring BootMyBatis和Druid的依赖。 2. 配置数据源:在application.properties文件中,配置并命名多个数据源,设置数据库连接等信息。 3. 创建数据源配置类:创建一个配置类,使用@Configuration注解将其标记为配置类,并使用@ConfigurationProperties注解将数据源属性注入。 4. 创建数据源:根据配置类中的属性,创建多个数据源,并将其加入到数据源路由器中。 5. 配置MyBatis:创建一个配置类,使用@MapperScan注解设置MyBatis的mapper接口路径,并将数据源注入到SqlSessionFactory中。 6. 配置分布式事务:使用@EnableTransactionManagement注解启用事务管理,并配置事务管理器。 7. 编写数据库操作代码:在mapper接口中定义数据库操作方法,并在Service层中调用这些方法进行数据库操作。 通过以上步骤,你就可以在Spring Boot项目中完成MyBatis和Druid的多数据源配置和分布式事务管理。不过需要注意的是,使用多数据源和分布式事务会增加项目的复杂性和性能开销,所以在使用之前需要仔细考虑是否真正需要这些功能。 ### 回答3: Spring Boot是一种快速构建Java应用程序的框架,MyBatis是一种流行的Java持久化框架,Druid是一种高性能的数据库连接池。本文将介绍如何在Spring Boot中使用MyBatis和Druid来实现多数据源和分布式事务。 要使用多个数据源,我们首先需要配置多个数据源。在Spring Boot中,我们可以通过在application.properties或者application.yml文件中配置多个数据源的连接信息。我们需要为每个数据源指定不同的URL、用户名和密码。然后,我们可以使用@Primary和@Qualifier来指定主数据源和其他数据源。 在配置数据源后,我们需要配置MyBatis来使用这些数据源。我们可以通过创建多个SqlSessionFactory来实现多数据源,然后在每个SqlSessionFactory中设置相应的数据源。我们还可以使用@MapperScan注解来自动扫描和注册Mapper接口。 在使用MyBatis和多个数据源时,我们可能会遇到事务管理的问题。为了解决这个问题,我们可以使用Spring Boot提供的@Transactional注解来标记需要进行事务管理的方法,然后Spring Boot会自动为我们处理事务。对于需要跨多个数据源进行事务管理的情况,我们可以使用JTA(Java Transaction API)实现分布式事务。在Spring Boot中,我们可以使用Atomikos或Bitronix等JTA提供商来实现分布式事务。 总结起来,使用Spring BootMyBatis和Druid,我们可以很容易地实现多数据源和分布式事务。通过正确配置数据源和使用相关注解,我们可以在几分钟内完成这些任务。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值