知识改变命运! SpringBoot系列15-mysql-multiple-data-sources1_猿份哥-lskyf博客社区

SpringBoot系列15-mysql-multiple-data-sources1

猿份哥 1年前 ⋅ 1669 阅读 ⋅ 0 个赞

springboot 多数据源的一个简单示例

多数据源分包加载

新建数据库test1和表tbl_user

CREATE TABLE `tbl_user` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

新建数据库test2和表tbl_order

CREATE TABLE `tbl_order` (
  `id` int(11) NOT NULL,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

数据源配置application.properties文件

## test1 database 配置
spring.datasource.test1.jdbc-url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.test1.username=root
spring.datasource.test1.password=root
spring.datasource.test1.driver-class-name=com.mysql.jdbc.Driver
## test2 database 配置
spring.datasource.test2.jdbc-url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.test2.username=root
spring.datasource.test2.password=root
spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver

加载配置

主库配置DataSourceConfig1.java


//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.yuanfenge.demo.dao.test01", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSourceConfig1 {
    // 将这个对象放入Spring容器中
    @Bean(name = "test1DataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "test1SqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)
        throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
            // 设置mybatis的xml所在位置
            new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test01/*.xml"));
        return bean.getObject();
    }
    @Bean("test1SqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate test1sqlsessiontemplate(
        @Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

从库配置DataSourceConfig2.java


@Configuration
@MapperScan(basePackages = "com.yuanfenge.demo.dao.test02", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSourceConfig2 {
    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource getDateSource2() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)
        throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/test02/*.xml"));
        return bean.getObject();
    }
    @Bean("test2SqlSessionTemplate")
    public SqlSessionTemplate test2sqlsessiontemplate(
        @Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }
}

测试controller


/**
 * @auth 猿份哥
 * @description
 * @createTime 2020 - 5 - 19 16:45
 */
@RestController
public class TestController {

    @Autowired
    TestService testService;

    @RequestMapping("/test")
    public Object test(){
        List<Order> list = testService.selectOrder();
        return list;
    }
    @RequestMapping("/test2")
    public Object test2(){
        int i = testService.saveOrder();
        String msg=i>0?"success":"failed";
        return msg;
    }

}

总结

分包加载不支持分布式事物,如果是多个数据库的事物@Transaction将会失效,所以使用这种方式要避免分布式事物。

源码下载链接

原文链接: https://www.lskyf.com/post/103

作者:猿份哥,版权所有,欢迎保留原文链接进行转载:)


全部评论: 0

    我有话说:

    Spring Boot系列1-helloword

      使用springboot简单轻松创建helloword SpringBoot系列1-helloword 关于springboot这是摘自官方的一段话 Spring Boot

    SpringBoot系列10-文件上传

    文章目录 1.先来最简单的 2.设置文件大小,请求大小 3.多文件上传 怎样使用最简单的方式上传文件,如何上传多个文件呢 先来最简单的 pom.xml文件引入依赖文件 <

    Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler

    介绍在SpringBoot中集成mybatis和druid以及自定义TypeHandler 创建数据库表 SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- --------------------...

    Spring Boot系列6-SpringBoot中使用servlet

    介绍在SpringBoot中如何使用servlet pom.xml <dependency> <groupId>org.springframework.boot<

    SpringBoot系列9-使用jasypt自定义stater运行时动态传入加密密码

    文章目录 1.新建springboot-encryption-configuration项目实现stater 2.pom文件引入jasypt 3.在resources/support/下配置

    spring boot系列4-定时任务-springboot自带的scheduled超级简单

    需求:创建一个每天凌晨0点执行的定时任务1.创建任务 /** * @author 天空蓝蓝的 */ @Slf4j @EnableScheduling @Component public class

    kubeshere创建mysql发生FailedCreate requested: requests.cpu=500m,requests.memory=2000Mi, used: requests

    1.错误日志 create Pod mysql-master-v1-0 in StatefulSet mysql-master-v1 failed error: pods "mysql-master

    面试题:MySQL参数innodb_flush_log_at_trx_commit有什么作用?

    面试题:MySQL参数innodb_flush_log_at_trx_commit有什么作用? innodb_flush_log_at_trx_commit是MySQL中InnoDB存储引擎的一个

    SpringBoot系列14-加载yml,properties配置文件信息

    yml前置知识 yml语法: 单个key value 写法 k:空格v eg: color: blue 对象写法 k: {k1: v1,k2: v2} k: k1: v1 k2: v2 list

    mysql5.7x升级到mysql8.0.3产生的错误

    错误日志 2023:05:03 01:10:36.305 ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper ? - Table 'db

    mysql function生成指定位数且不重复数字

    1.生成指定位数且不重复数字 2.函数结构 CREATE DEFINER=`root`@`%` FUNCTION `fun_sn`(number BIGINT) RETURNS bigint(20

    freemarker input date 或datetime-local不显示怎么办?

    freemarker input date 或datetime-local不显示怎么办? 在模板页面加上要显示的格式:例如:<#setting datetime_format="yyyy-MM

    java高频面试题-mysql的InnoDB与MyISAM存储引擎有哪些区别 ?

    mysql的InnoDB与MyISAM存储引擎有哪些区别 ? MySQL是一个广泛使用的关系型数据库管理系统,其中InnoDB和MyISAM是两种常用的存储引擎。它们在功能和性能方面存在着显著的差异

    spring boot项目本地没问题,部署到服务器mysql报错:errorCode 0, state 08S01

    错误现象: 在开发的时候没有报错,能正常运行并且能连接服务器。但是部署到服务器报错。 错误如下: 2023-04-07 11:54:40.617 ERROR 7 --- [reate

    加入公众号
    加入公众号