当前位置:   article > 正文

Spring Boot 多数据源配置

Spring Boot 多数据源配置

1. 项目结构

  1. src
  2. ├── main
  3. │ ├── java
  4. │ │ └── org
  5. │ │ └── songtang
  6. │ │ └── springbootdynamic
  7. │ │ ├── config
  8. │ │ ├── controller
  9. │ │ ├── entity
  10. │ │ ├── mapper
  11. │ │ │ ├── master
  12. │ │ │ └── slave
  13. │ │ └── service
  14. │ └── resources
  15. │ └── mapper
  16. │ ├── master
  17. │ └── slave
  18. └── test

pom配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>3.3.2</version>
  10. <relativePath/>
  11. </parent>
  12. <groupId>org.songtang</groupId>
  13. <artifactId>springboot-dynamic</artifactId>
  14. <version>0.0.1-SNAPSHOT</version>
  15. <properties>
  16. <java.version>17</java.version>
  17. <mysql.version>8.4.0</mysql.version>
  18. <mybatisplus.version>3.5.7</mybatisplus.version>
  19. </properties>
  20. <dependencies>
  21. <!-- SpringBoot相关 -->
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <!--mybatisplus-->
  31. <dependency>
  32. <groupId>com.baomidou</groupId>
  33. <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
  34. <version>${mybatisplus.version}</version>
  35. </dependency>
  36. <!--mysql 数据库相关-->
  37. <dependency>
  38. <groupId>com.mysql</groupId>
  39. <artifactId>mysql-connector-j</artifactId>
  40. <version>${mysql.version}</version>
  41. </dependency>
  42. <dependency>
  43. <groupId>com.zaxxer</groupId>
  44. <artifactId>HikariCP</artifactId>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. <dependency>
  52. <groupId>org.projectlombok</groupId>
  53. <artifactId>lombok</artifactId>
  54. <version>1.18.34</version>
  55. </dependency>
  56. </dependencies>
  57. <build>
  58. <plugins>
  59. <plugin>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-maven-plugin</artifactId>
  62. <configuration>
  63. <excludes>
  64. <exclude>
  65. <groupId>org.projectlombok</groupId>
  66. <artifactId>lombok</artifactId>
  67. </exclude>
  68. </excludes>
  69. </configuration>
  70. </plugin>
  71. </plugins>
  72. <resources>
  73. <resource>
  74. <directory>src/main/resources</directory>
  75. <includes>
  76. <include>**/*.*</include>
  77. </includes>
  78. </resource>
  79. </resources>
  80. </build>
  81. </project>

2. 数据源配置类 (DataSourceConfig)

此类用于配置多个数据源,并将其分别标记为 PrimarySecondary,以便在需要时进行区分。

  1. package org.songtang.springbootdynamic.config;
  2. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import org.springframework.boot.jdbc.DataSourceBuilder;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.context.annotation.Primary;
  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  11. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  12. import javax.sql.DataSource;
  13. @Configuration
  14. public class DataSourceConfig {
  15. @Primary
  16. @Bean(name = "mainDateSource")
  17. @ConfigurationProperties(prefix = "spring.datasource.main")
  18. public DataSource mainDateSource(){
  19. return DataSourceBuilder.create().build();
  20. }
  21. @Bean(name = "targetDateSource")
  22. @ConfigurationProperties(prefix = "spring.datasource.target")
  23. public DataSource targetDateSource(){
  24. return DataSourceBuilder.create().build();
  25. }
  26. @Primary
  27. @Bean(name = "mainSessionFactory")
  28. public SqlSessionFactory mainSessionFactory(@Qualifier("mainDateSource")DataSource dataSource) throws Exception{
  29. MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
  30. mybatisSqlSessionFactoryBean.setDataSource(dataSource);
  31. mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
  32. return mybatisSqlSessionFactoryBean.getObject();
  33. }
  34. @Bean(name = "targetSessionFactory")
  35. public SqlSessionFactory SessionFactory(@Qualifier("targetDateSource")DataSource dataSource) throws Exception{
  36. MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
  37. sqlSessionFactoryBean.setDataSource(dataSource);
  38. sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml"));
  39. return sqlSessionFactoryBean.getObject();
  40. }
  41. @Bean(name = "mainTransactionManager")
  42. public DataSourceTransactionManager mainTransactionManager(@Qualifier("mainDateSource") DataSource dataSource) {
  43. return new DataSourceTransactionManager(dataSource);
  44. }
  45. @Bean(name = "targetTransactionManager")
  46. public DataSourceTransactionManager targetTransactionManager(@Qualifier("targetDateSource") DataSource dataSource) {
  47. return new DataSourceTransactionManager(dataSource);
  48. }
  49. }

3. 数据源映射配置类

MasterMapperConfigSlaveMapperConfig 分别配置主数据源和从数据源的 Mapper

主数据源配置 (MasterMapperConfig)

  1. package org.songtang.springbootdynamic.config;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @MapperScan(basePackages = "org.songtang.springbootdynamic.mapper.master", sqlSessionFactoryRef = "mainSessionFactory")
  6. public class MasterMapperConfig {
  7. }

从数据源配置 (SlaveMapperConfig)

  1. package org.songtang.springbootdynamic.config;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @MapperScan(basePackages = "org.songtang.springbootdynamic.mapper.slave", sqlSessionFactoryRef = "targetSessionFactory")
  6. public class SlaveMapperConfig {
  7. }

4. 实体类 (Member)

Member 实体类用于表示数据库中的成员数据,并与 masterslave 两个数据源交互。

  1. package org.songtang.springbootdynamic.entity;
  2. import com.baomidou.mybatisplus.annotation.TableName;
  3. import lombok.Data;
  4. @TableName("member")
  5. @Data
  6. public class Member extends BaseEntity{
  7. private String name;
  8. private String phone;
  9. private Double amount;
  10. }

5. Mapper 接口

Mapper 接口用于定义与数据库交互的方法。

主数据源 Mapper (MasterMapper)

  1. package org.songtang.springbootdynamic.mapper.master;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.songtang.springbootdynamic.entity.Member;
  5. @Mapper
  6. public interface MasterMapper extends BaseMapper<Member> {
  7. // 主数据源相关操作
  8. }

从数据源 Mapper (SlaveMapper)

  1. package org.songtang.springbootdynamic.mapper.slave;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import org.apache.ibatis.annotations.Mapper;
  4. import org.songtang.springbootdynamic.entity.Member;
  5. @Mapper
  6. public interface SlaveMapper extends BaseMapper<Member> {
  7. // 从数据源相关操作
  8. }

6. 控制器 (Controller)

控制器类用于定义对外暴露的 API 接口,用于操作不同数据源的数据。

  1. package org.songtang.springbootdynamic.controller;
  2. import org.songtang.springbootdynamic.entity.Member;
  3. import org.songtang.springbootdynamic.service.YourService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. import java.util.List;
  7. @RestController
  8. @RequestMapping("/api")
  9. public class MultiDataSourceController {
  10. @Autowired
  11. private YourService yourService;
  12. // 使用主数据源插入数据
  13. @PostMapping("/master")
  14. public void addMasterEntity(@RequestBody Member masterEntity) {
  15. yourService.addMaster(masterEntity);
  16. }
  17. // 使用从数据源插入数据
  18. @PostMapping("/slave")
  19. public void addSlaveEntity(@RequestBody Member slaveEntity) {
  20. yourService.addSlave(slaveEntity);
  21. }
  22. }

7. 使用示例

在项目中,可以通过调用控制器的 API 来测试不同数据源的功能:

  • 插入主数据源的数据: 通过 /api/master 接口插入数据
  • 插入从数据源的数据: 通过 /api/slave 接口插入数据

8. application.yml 配置 

application.yml 文件中需要配置主数据源和从数据源的连接信息:

  1. spring:
  2. datasource:
  3. main:
  4. url: jdbc:mysql://localhost:3306/masterdb
  5. username: root
  6. password: root
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. target:
  9. url: jdbc:mysql://localhost:3306/slavedb
  10. username: root
  11. password: root
  12. driver-class-name: com.mysql.cj.jdbc.Driver

总结

通过以上配置,您可以在 Spring Boot 项目中成功实现多数据源的管理,分离不同的数据库操作。这样可以轻松处理不同数据源之间的事务以及数据交互,确保应用的高效性和可扩展性。

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号