• springboot 简单配置mongodb多数据源


    准备工作:

    1. 本地mongodb一个
    2. 创建两个数据库 student 和 student-two

    所需jar包:

    1. # springboot基于的版本
    2. org.springframework.boot
    3. spring-boot-starter-parent
    4. 2.2.1.RELEASE
    5. # maven 关键jar包
    6. org.springframework.boot
    7. spring-boot-starter-web
    8. org.projectlombok
    9. lombok
    10. true
    11. org.springframework.boot
    12. spring-boot-starter-data-mongodb
    13. org.springframework.boot
    14. spring-boot-configuration-processor
    15. true

    配置文件:

    1. # uri 配置样例: mongodb://myDBReader:DifficultPassword@mongodb0.example.com:27017/admin
    2. # 如果用户名或密码包含at符号@,冒号:,斜杠/或百分号%字符,请使用百分比编码方式消除歧义
    3. # uri 集群配置样例: mongodb://myDBReader:D1fficultP%40ssw0rd@mongodb0.example.com:27017,mongodb1.example.com:27017,mongodb2.example.com:27017/admin?replicaSet=myRepl
    4. douzi:
    5. mongo:
    6. primary:
    7. uri: mongodb://127.0.0.1:27017/student
    8. repository-package: com.douzi.mongo.dao.primary
    9. secondary:
    10. uri: mongodb://127.0.0.1:27017/student-two
    11. repository-package: com.douzi.mongo.dao.secondary

    多数据源配置类 MultipleMongoConfig:

    1. package com.douzi.mongo.config;
    2. import org.springframework.beans.factory.annotation.Qualifier;
    3. import org.springframework.beans.factory.annotation.Value;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.context.annotation.Configuration;
    6. import org.springframework.context.annotation.Primary;
    7. import org.springframework.data.mongodb.MongoDbFactory;
    8. import org.springframework.data.mongodb.core.MongoTemplate;
    9. import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
    10. import org.springframework.util.StringUtils;
    11. import com.mongodb.MongoClientURI;
    12. /**
    13. * @Author douzi
    14. * @Title: MultipleMongoConfig
    15. * @Description: 读取对应的配置信息并且构造对应的MongoTemplate
    16. * @Date 2023-09-27
    17. */
    18. @Configuration
    19. public class MultipleMongoConfig {
    20. @Value("${douzi.mongo.primary.uri}")
    21. private String primaryUri;
    22. @Value("${douzi.mongo.secondary.uri}")
    23. private String secondaryUri;
    24. /**
    25. * 配置主数据源template
    26. * @return 主数据源template
    27. */
    28. @Primary
    29. @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    30. public MongoTemplate primaryMongoTemplate() {
    31. return new MongoTemplate(primaryFactory());
    32. }
    33. /**
    34. * 配置从数据源template
    35. * @return 从数据源template
    36. */
    37. @Bean
    38. @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
    39. public MongoTemplate secondaryMongoTemplate() {
    40. return new MongoTemplate(secondaryFactory());
    41. }
    42. /**
    43. * 配置主数据源db工厂
    44. * @param mongo 属性配置信息
    45. * @return 主数据源db工厂
    46. */
    47. @Bean
    48. @Primary
    49. public MongoDbFactory primaryFactory() {
    50. if (StringUtils.isEmpty(primaryUri)) {
    51. throw new RuntimeException("必须配置mongo primary Uri");
    52. }
    53. return new SimpleMongoDbFactory(new MongoClientURI(primaryUri));
    54. }
    55. /**
    56. * 配置从数据源db工厂
    57. * @param mongo 属性配置信息
    58. * @return 从数据源db工厂
    59. */
    60. @Bean
    61. public MongoDbFactory secondaryFactory() {
    62. return new SimpleMongoDbFactory(new MongoClientURI(secondaryUri));
    63. }
    64. }

     主数据源配置 PrimaryMongoConfig:

    1. package com.douzi.mongo.config;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
    4. /**
    5. * @Author douzi
    6. * @Title: PrimaryMongoConfig
    7. * @Description: 主数据源配置
    8. * @date 2023-09-27
    9. */
    10. @Configuration
    11. @EnableMongoRepositories(basePackages = "${douzi.mongo.primary.repository-package}", mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
    12. public class PrimaryMongoConfig {
    13. protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
    14. }

    副数据源配置 SecondaryMongoConfig:

    1. package com.douzi.mongo.config;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
    4. /**
    5. * @Author douzi
    6. * @Title: SecondaryMongoConfig
    7. * @Description: 从数据源配置
    8. * @Date 2023-09-27
    9. */
    10. @Configuration
    11. @EnableMongoRepositories(basePackages = "${douzi.mongo.secondary.repository-package}", mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
    12. public class SecondaryMongoConfig {
    13. protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
    14. }

    以下是辅助测试类 高手可以自行测试:

    dao层:

    1. package com.douzi.mongo.dao.primary;
    2. import lombok.Data;
    3. import org.springframework.data.annotation.Id;
    4. import org.springframework.data.mongodb.core.mapping.Document;
    5. import java.io.Serializable;
    6. import java.math.BigDecimal;
    7. import java.util.Date;
    8. /**
    9. * @Author douzi
    10. * @Title: PrimaryStudent
    11. * @Description: 主数据源学生对象
    12. * @Date 2023/09/24 13:33
    13. */
    14. @Data
    15. @Document(collection = "first_students")
    16. public class PrimaryStudent implements Serializable {
    17. /**
    18. * id
    19. */
    20. @Id
    21. private Integer id;
    22. /**
    23. * 姓名
    24. */
    25. private String name;
    26. /**
    27. * 生活费
    28. */
    29. private BigDecimal salary;
    30. /**
    31. * 生日
    32. */
    33. private Date birth;
    34. }
    35. ##################################分隔符########################################
    36. package com.douzi.mongo.dao.primary;
    37. import org.springframework.data.mongodb.repository.MongoRepository;
    38. /**
    39. * @Author douzi
    40. * @Title: PrimaryRepository
    41. * @Description: 主数据源dao层
    42. * @Date 2023/09/24 16:01
    43. */
    44. public interface PrimaryRepository extends MongoRepository {
    45. /**
    46. * 通过名字查找学生
    47. *
    48. * @param name 名字
    49. * @return 学生信息
    50. */
    51. PrimaryStudent findByName(String name);
    52. /**
    53. * 通过名字删除学生
    54. *
    55. * @param name 名字
    56. * @return 学生信息
    57. */
    58. PrimaryStudent removeStudentByName(String name);
    59. }
    60. ##################################分隔符########################################
    61. package com.douzi.mongo.dao.secondary;
    62. import lombok.Data;
    63. import org.springframework.data.annotation.Id;
    64. import org.springframework.data.mongodb.core.mapping.Document;
    65. import java.io.Serializable;
    66. import java.math.BigDecimal;
    67. import java.util.Date;
    68. /**
    69. *
    70. * @Author douzi
    71. * @Title: PrimaryStudent
    72. * @Description: 副数据源学生对象
    73. * @Date 2023/09/24 13:33
    74. */
    75. @Data
    76. @Document(collection = "secondary_students")
    77. public class SecondaryStudent implements Serializable {
    78. /**
    79. * id
    80. */
    81. @Id
    82. private Integer id;
    83. /**
    84. * 姓名
    85. */
    86. private String name;
    87. /**
    88. * 生活费
    89. */
    90. private BigDecimal salary;
    91. /**
    92. * 生日
    93. */
    94. private Date birth;
    95. }
    96. ##################################分隔符########################################
    97. package com.douzi.mongo.dao.secondary;
    98. import org.springframework.data.mongodb.repository.MongoRepository;
    99. /**
    100. * @Author douzi
    101. * @Title: SecondaryRepository
    102. * @Description: 从数据源dao层
    103. * @Date 2023/09/24 16:02
    104. */
    105. public interface SecondaryRepository extends MongoRepository {
    106. /**
    107. * 通过名字查找学生
    108. *
    109. * @param name 名字
    110. * @return 学生信息
    111. */
    112. SecondaryStudent findByName(String name);
    113. /**
    114. * 通过名字删除学生
    115. *
    116. * @param name 名字
    117. * @return 学生信息
    118. */
    119. SecondaryStudent removeStudentByName(String name);
    120. }

    Service层:

    1. package com.douzi.mongo.service;
    2. import com.douzi.mongo.dao.primary.PrimaryRepository;
    3. import com.douzi.mongo.dao.primary.PrimaryStudent;
    4. import com.douzi.mongo.dao.secondary.SecondaryRepository;
    5. import com.douzi.mongo.dao.secondary.SecondaryStudent;
    6. import lombok.extern.slf4j.Slf4j;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Service;
    9. import java.util.List;
    10. /**
    11. *
    12. * @Author douzi
    13. * @Title: StudentService
    14. * @Description:
    15. * @Date 2023/09/24 14:32
    16. */
    17. @Service
    18. @Slf4j
    19. public class StudentService {
    20. @Autowired
    21. private PrimaryRepository primaryRepository;
    22. @Autowired
    23. private SecondaryRepository secondaryRepository;
    24. /**
    25. * 保存学生
    26. *
    27. * @param primaryStudent
    28. * @param secondaryStudent
    29. */
    30. public void save(PrimaryStudent primaryStudent, SecondaryStudent secondaryStudent) {
    31. PrimaryStudent student1 = primaryRepository.insert(primaryStudent);
    32. log.info(student1.toString());
    33. SecondaryStudent student2 = secondaryRepository.insert(secondaryStudent);
    34. log.info(student2.toString());
    35. }
    36. /**
    37. * 删除学生
    38. *
    39. * @param name
    40. * @return
    41. */
    42. public void delete(String name) {
    43. primaryRepository.deleteById(1);
    44. secondaryRepository.deleteById(1);
    45. }
    46. /**
    47. * 修改学生
    48. *
    49. * @param primaryStudent
    50. * @param secondaryStudent
    51. */
    52. public void update(PrimaryStudent primaryStudent, SecondaryStudent secondaryStudent) {
    53. PrimaryStudent student1 = primaryRepository.save(primaryStudent);
    54. log.info(student1.toString());
    55. SecondaryStudent student2 = secondaryRepository.save(secondaryStudent);
    56. log.info(student2.toString());
    57. }
    58. /**
    59. * 查找学生
    60. *
    61. * @param name 学生姓名
    62. * @return
    63. */
    64. public void find(String name) {
    65. PrimaryStudent student1 = primaryRepository.findByName(name);
    66. log.info(student1.toString());
    67. SecondaryStudent student2 = secondaryRepository.findByName(name);
    68. log.info(student2.toString());
    69. }
    70. /**
    71. * 查找学生集合
    72. *
    73. * @return 学生集合
    74. */
    75. public void findAll() {
    76. List primaryRepositoryAll = primaryRepository.findAll();
    77. log.info(primaryRepositoryAll.toString());
    78. List secondaryRepositoryAll = secondaryRepository.findAll();
    79. log.info(secondaryRepositoryAll.toString());
    80. }
    81. }

    Controller层:

    1. package com.douzi.mongo.controller;
    2. import com.douzi.mongo.dao.primary.PrimaryStudent;
    3. import com.douzi.mongo.dao.secondary.SecondaryStudent;
    4. import com.douzi.mongo.service.StudentService;
    5. import org.springframework.beans.BeanUtils;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import java.math.BigDecimal;
    10. import java.util.Date;
    11. /**
    12. * @Author douzi
    13. * @Title: StudentController
    14. * @Description:
    15. * @Date 2023/09/24 14:53
    16. */
    17. @RestController
    18. @RequestMapping("/student")
    19. public class StudentController {
    20. @Autowired
    21. private StudentService studentService;
    22. /**
    23. * 保存学生
    24. *
    25. * @return 保存的学生
    26. */
    27. @RequestMapping("/save")
    28. public void save() {
    29. PrimaryStudent primaryStudent = new PrimaryStudent();
    30. SecondaryStudent secondaryStudent = new SecondaryStudent();
    31. primaryStudent.setId(1);
    32. primaryStudent.setName("mongo");
    33. primaryStudent.setSalary(BigDecimal.valueOf(1000));
    34. primaryStudent.setBirth(new Date());
    35. BeanUtils.copyProperties(primaryStudent, secondaryStudent);
    36. studentService.save(primaryStudent, secondaryStudent);
    37. }
    38. /**
    39. * 修改学生
    40. *
    41. * @return 修改结果
    42. */
    43. @RequestMapping("/update")
    44. public void update() {
    45. PrimaryStudent primaryStudent = new PrimaryStudent();
    46. SecondaryStudent secondaryStudent = new SecondaryStudent();
    47. primaryStudent.setId(1);
    48. primaryStudent.setName("mongo");
    49. primaryStudent.setSalary(BigDecimal.valueOf(2000));
    50. primaryStudent.setBirth(new Date());
    51. BeanUtils.copyProperties(primaryStudent, secondaryStudent);
    52. studentService.update(primaryStudent, secondaryStudent);
    53. }
    54. /**
    55. * 根据姓名删除学生
    56. *
    57. * @param name 姓名
    58. * @return 删除结果
    59. */
    60. @RequestMapping("/delete")
    61. public void delete(String name) {
    62. studentService.delete(name);
    63. }
    64. /**
    65. * 通过名字查找学生
    66. *
    67. * @param name 学生名
    68. * @return 学生信息
    69. */
    70. @RequestMapping("/find")
    71. public void find(String name) {
    72. studentService.find(name);
    73. }
    74. /**
    75. * 查找所有学生
    76. *
    77. * @return 学生集合
    78. */
    79. @RequestMapping("/all")
    80. public void findAll() {
    81. studentService.findAll();
    82. }
    83. }

    测试:

    http://localhost:8080/student/save

    结果:

  • 相关阅读:
    使用golang+antlr4构建一个自己的语言解析器(一)
    什么是单片机?聊聊它的历史
    mysql
    基于轩禹秒杀ctfshow-RSA
    在面试提问环节应该问那些内容
    “蔚来杯“2022牛客暑期多校训练营6 C题: Forest
    测试用例评审的旁观记录
    Ubuntu 22.04 下 CURL(C++) 实现分块上传/下载文件源码
    (一)JDK、转义字符、数据类型
    使去中心化媒体网络相关联的NFT元数据标准
  • 原文地址:https://blog.csdn.net/qq_16116549/article/details/133344312