1.单数据源(单节点)

引入依赖

  1. <!--mongodb依赖-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  5. </dependency>
  6. <!--Lombok-->
  7. <dependency>
  8. <groupId>org.projectlombok</groupId>
  9. <artifactId>lombok</artifactId>
  10. <optional>true</optional>
  11. </dependency>

也可以在创建boot项目时,在noSql中选择Mongo即可
image.png

添加配置

在yml下添加如下内容,如果没有权限控制,那么不写用户名和密码即可

  1. spring:
  2. data:
  3. mongodb:
  4. host: 120.48.107.224
  5. port: 27017
  6. username: "ftc"
  7. password: "1213456"
  8. database: java_test

也可以通过url形式进行链接

  1. spring:
  2. data:
  3. mongodb:
  4. username: "ftc"
  5. password: "1213456"
  6. uri: mongodb://120.48.107.224:27017/java_test

添加监听器

如果不创建监听器的话,spring-data-mongo会默认为每个文档添加名为_class的键,值为文档对应类的包路径
添加监听器后,就不会创建默认列了,如图:
image.png
监听器代码如下

  1. import org.springframework.context.ApplicationListener;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.context.event.ContextRefreshedEvent;
  4. import org.springframework.data.mongodb.core.MongoTemplate;
  5. import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  6. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  7. import org.springframework.data.mongodb.core.convert.MongoConverter;
  8. import javax.annotation.Resource;
  9. /**
  10. * @author 冯铁城 [17615007230@163.com]
  11. * @date 2022-07-20 19:26:10
  12. * @describe: mongodb监听器
  13. */
  14. @Configuration
  15. public class MongoReadyListener implements ApplicationListener<ContextRefreshedEvent> {
  16. /**
  17. * spring-data-mongo会默认为每个文档添加的键,值为文档对应类的包路径,例如:com.ftc.redistry.mongo.Student
  18. */
  19. private static final String TYPEKEY = "_class";
  20. @Resource
  21. MongoTemplate oneMongoTemplate;
  22. @Override
  23. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
  24. MongoConverter converter = oneMongoTemplate.getConverter();
  25. if (converter.getTypeMapper().isTypeKey(TYPEKEY)) {
  26. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
  27. }
  28. }
  29. }

创建对应文档类

注意点如下:

  1. 如果不创建格式规范的文档类,自由存储数据类型,那么就会创建对应的数据类型集合,例如存入一个JSONObject对象,就会创建一个名为JSONObject的集合
  2. 通过@Document注解加在类上,声明一个实体类对应的集合是哪个集合。例如@Document(collection = “student”),那么该实体类对应的集合为student
  3. 主键ID字段最好设置为String类型,因为mongo自动生成的主键ID长达24位,其他数据类型不好承接,String类型比较方便

文档类具体代码如下

  1. import lombok.Data;
  2. import org.springframework.data.mongodb.core.mapping.Document;
  3. /**
  4. * @author 冯铁城 [17615007230@163.com]
  5. * @date 2022-07-20 19:12:01
  6. * @describe: MongoDB实体类
  7. * <p>
  8. * “@Document(collection = "student")” 用于指定对应哪个集合
  9. */
  10. @Data
  11. @Document(collection = "student")
  12. public class Student {
  13. private String id;
  14. private String name;
  15. private int age;
  16. }

操作示例

通过mongoTemplate操作即可

  1. import cn.hutool.core.lang.Console;
  2. import com.ftc.redistry.mongo.Student;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.data.mongodb.core.MongoTemplate;
  7. /**
  8. * @author 冯铁城 [17615007230@163.com]
  9. * @date 2022-07-20 19:18:24
  10. * @describe:
  11. */
  12. @SpringBootTest
  13. public class MongoDbTest {
  14. @Autowired
  15. private MongoTemplate mongoTemplate;
  16. @Test
  17. void testInsert() {
  18. //1.创建对象指定ID
  19. Student student = new Student();
  20. student.setId("2222");
  21. student.setName("ftc1111");
  22. student.setAge(13);
  23. Student insert = mongoTemplate.insert(student);
  24. Console.log(insert);
  25. //2.创建对象不指定ID
  26. Student student1 = new Student();
  27. student1.setName("ftc1111");
  28. student1.setAge(13);
  29. Student insert1 = mongoTemplate.insert(student1);
  30. Console.log(insert1);
  31. }
  32. }

2.多数据源(单节点)

引入依赖

  1. <!--mongodb依赖-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-mongodb</artifactId>
  5. </dependency>
  6. <!--Lombok-->
  7. <dependency>
  8. <groupId>org.projectlombok</groupId>
  9. <artifactId>lombok</artifactId>
  10. <optional>true</optional>
  11. </dependency>
  12. <!--Hutool依赖-->
  13. <dependency>
  14. <groupId>cn.hutool</groupId>
  15. <artifactId>hutool-all</artifactId>
  16. <version>5.8.4</version>
  17. </dependency>

也可以在创建boot项目时,在noSql中选择Mongo即可
image.png

添加配置

数据的配置格式可自定义,下文只提供参考,当然也可以直接借鉴获取
还有其他参数,例如链接时间等,这些可以具体情况具体安排

  1. spring:
  2. data:
  3. mongodb:
  4. #主数据源
  5. primary:
  6. address:
  7. - 120.48.107.224:27017
  8. - 120.48.107.224:27018
  9. username: "java_test"
  10. password: "java_test"
  11. database: java_test
  12. #备数据源
  13. secondary:
  14. address:
  15. - 120.48.107.224:27017
  16. - 120.48.107.224:27018
  17. username: "java_test_bak"
  18. password: "java_test_bak"
  19. database: java_test_bak

添加配置类

  1. import lombok.Data;
  2. import java.util.List;
  3. /**
  4. * @author: 冯铁城 [17615007230@163.com]
  5. * @date: 2022-07-29 15:40:07
  6. * @describe: mongo配置属性
  7. */
  8. @Data
  9. public class MongoConfigProperties {
  10. /**
  11. * 数据源地址集合 格式{host}:{port}
  12. */
  13. private List<String> address;
  14. /**
  15. * 用户名
  16. */
  17. private String username;
  18. /**
  19. * 密码
  20. */
  21. private String password;
  22. /**
  23. * 数据库名称
  24. */
  25. private String database;
  26. }

添加不同数据源自定义配置

  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.Primary;
  5. /**
  6. * @author: 冯铁城 [17615007230@163.com]
  7. * @date: 2022-07-29 15:41:02
  8. * @describe: mongo配置类
  9. */
  10. @Configuration
  11. public class MongoConfig {
  12. @Primary
  13. @Bean(name = "primaryMongoProperties")
  14. @ConfigurationProperties(prefix = "spring.data.mongodb.primary")
  15. public MongoConfigProperties primaryMongoProperties() {
  16. return new MongoConfigProperties();
  17. }
  18. @Bean(name = "secondaryMongoProperties")
  19. @ConfigurationProperties(prefix = "spring.data.mongodb.secondary")
  20. public MongoConfigProperties secondaryMongoProperties() {
  21. return new MongoConfigProperties();
  22. }
  23. }

添加主数据源配置

  1. import cn.hutool.core.util.StrUtil;
  2. import com.mongodb.MongoClientSettings;
  3. import com.mongodb.MongoCredential;
  4. import com.mongodb.ReadPreference;
  5. import com.mongodb.ServerAddress;
  6. import com.mongodb.client.MongoClients;
  7. import com.mongodb.connection.ConnectionPoolSettings;
  8. import org.springframework.beans.factory.annotation.Qualifier;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.Primary;
  12. import org.springframework.data.mongodb.MongoTransactionManager;
  13. import org.springframework.data.mongodb.core.MongoTemplate;
  14. import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
  15. import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  16. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  17. import org.springframework.data.mongodb.core.convert.MongoConverter;
  18. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
  19. import javax.annotation.Resource;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import java.util.concurrent.TimeUnit;
  23. /**
  24. * @author: 冯铁城 [17615007230@163.com]
  25. * @date: 2022-07-29 15:44:02
  26. * @describe: mongo主数据源各种配置类
  27. */
  28. @Configuration
  29. @EnableMongoRepositories(basePackages = "com.ftc.mongotest", mongoTemplateRef = "primaryTemplate")
  30. public class PrimaryMongoTemplate {
  31. @Resource
  32. @Qualifier("primaryMongoProperties")
  33. private MongoConfigProperties primaryProperties;
  34. @Primary
  35. @Bean(name = "primaryTemplate")
  36. public MongoTemplate primaryTemplate() {
  37. //1.获取primaryTemplate
  38. SimpleMongoClientDatabaseFactory primaryFactory = getFactory(this.primaryProperties);
  39. MongoTemplate primaryTemplate = new MongoTemplate(primaryFactory);
  40. //2.默认数据源监听处理
  41. String type = "_class";
  42. MongoConverter converter = primaryTemplate.getConverter();
  43. if (converter.getTypeMapper().isTypeKey(type)) {
  44. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
  45. }
  46. //3.返回
  47. return primaryTemplate;
  48. }
  49. @Bean(name = "primaryMongoTransactionManager")
  50. public MongoTransactionManager userTransactionManager() {
  51. SimpleMongoClientDatabaseFactory factory = getFactory(this.primaryProperties);
  52. return new MongoTransactionManager(factory);
  53. }
  54. @Primary
  55. @Bean("primaryFactory")
  56. public SimpleMongoClientDatabaseFactory getFactory(MongoConfigProperties properties) {
  57. //1.设置链接地址
  58. List<ServerAddress> hosts = new ArrayList<>();
  59. properties.getAddress().forEach(address -> {
  60. List<String> addressInfos = StrUtil.split(address, StrUtil.COLON);
  61. hosts.add(new ServerAddress(addressInfos.get(0), Integer.parseInt(addressInfos.get(1))));
  62. });
  63. //2.初始化连接池参数
  64. ConnectionPoolSettings poolSetting = ConnectionPoolSettings
  65. .builder()
  66. .maxWaitTime(10000, TimeUnit.MILLISECONDS)
  67. .build();
  68. //3.构造基础链接参数
  69. MongoClientSettings.Builder settingBuilder = MongoClientSettings
  70. .builder()
  71. .applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
  72. .applyToClusterSettings(builder -> builder.hosts(hosts));
  73. //4.初始链接参数以及连接池参数
  74. MongoClientSettings settings;
  75. //5.根据用户名是否为空判定是否鉴权
  76. if (StrUtil.isNotBlank(properties.getUsername())) {
  77. //6.添加授权参数
  78. MongoCredential credential = MongoCredential.createScramSha1Credential(
  79. properties.getUsername(), properties.getDatabase(), properties.getPassword().toCharArray()
  80. );
  81. //7.添加链接参数
  82. settings = settingBuilder.credential(credential).build();
  83. } else {
  84. //7.添加链接参数
  85. settings = settingBuilder.build();
  86. }
  87. //8.创建工厂返回
  88. return new SimpleMongoClientDatabaseFactory(MongoClients.create(settings), properties.getDatabase());
  89. }
  90. }

添加备数据源配置

  1. import cn.hutool.core.util.StrUtil;
  2. import com.mongodb.MongoClientSettings;
  3. import com.mongodb.MongoCredential;
  4. import com.mongodb.ReadPreference;
  5. import com.mongodb.ServerAddress;
  6. import com.mongodb.client.MongoClients;
  7. import com.mongodb.connection.ConnectionPoolSettings;
  8. import org.springframework.beans.factory.annotation.Qualifier;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.data.mongodb.MongoTransactionManager;
  12. import org.springframework.data.mongodb.core.MongoTemplate;
  13. import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
  14. import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
  15. import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
  16. import org.springframework.data.mongodb.core.convert.MongoConverter;
  17. import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
  18. import javax.annotation.Resource;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import java.util.concurrent.TimeUnit;
  22. /**
  23. * @author: 冯铁城 [17615007230@163.com]
  24. * @date: 2022-07-29 15:44:02
  25. * @describe: mongo主数据源各种配置类
  26. */
  27. @Configuration
  28. @EnableMongoRepositories(basePackages = "com.ftc.mongotest", mongoTemplateRef = "secondaryTemplate")
  29. public class SecondaryMongoTemplate {
  30. @Resource
  31. @Qualifier("secondaryMongoProperties")
  32. private MongoConfigProperties secondaryProperties;
  33. @Bean(name = "secondaryTemplate")
  34. public MongoTemplate secondaryTemplate() {
  35. //1.获取primaryTemplate
  36. SimpleMongoClientDatabaseFactory primaryFactory = getFactory(this.secondaryProperties);
  37. MongoTemplate primaryTemplate = new MongoTemplate(primaryFactory);
  38. //2.默认数据源监听处理
  39. String type = "_class";
  40. MongoConverter converter = primaryTemplate.getConverter();
  41. if (converter.getTypeMapper().isTypeKey(type)) {
  42. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
  43. }
  44. //3.返回
  45. return primaryTemplate;
  46. }
  47. @Bean(name = "secondaryMongoTransactionManager")
  48. public MongoTransactionManager userTransactionManager() {
  49. SimpleMongoClientDatabaseFactory factory = getFactory(this.secondaryProperties);
  50. return new MongoTransactionManager(factory);
  51. }
  52. @Bean("secondaryFactory")
  53. public SimpleMongoClientDatabaseFactory getFactory(MongoConfigProperties properties) {
  54. //1.设置链接地址
  55. List<ServerAddress> hosts = new ArrayList<>();
  56. properties.getAddress().forEach(address -> {
  57. List<String> addressInfos = StrUtil.split(address, StrUtil.COLON);
  58. hosts.add(new ServerAddress(addressInfos.get(0), Integer.parseInt(addressInfos.get(1))));
  59. });
  60. //2.初始化连接池参数
  61. ConnectionPoolSettings poolSetting = ConnectionPoolSettings
  62. .builder()
  63. .maxWaitTime(10000, TimeUnit.MILLISECONDS)
  64. .build();
  65. //3.构造基础链接参数
  66. MongoClientSettings.Builder settingBuilder = MongoClientSettings
  67. .builder()
  68. .applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
  69. .applyToClusterSettings(builder -> builder.hosts(hosts));
  70. //4.初始链接参数以及连接池参数
  71. MongoClientSettings settings;
  72. //5.根据用户名是否为空判定是否鉴权
  73. if (StrUtil.isNotBlank(properties.getUsername())) {
  74. //6.添加授权参数
  75. MongoCredential credential = MongoCredential.createScramSha1Credential(
  76. properties.getUsername(), properties.getDatabase(), properties.getPassword().toCharArray()
  77. );
  78. //7.添加链接参数
  79. settings = settingBuilder.credential(credential).build();
  80. } else {
  81. //7.添加链接参数
  82. settings = settingBuilder.build();
  83. }
  84. //8.创建工厂返回
  85. return new SimpleMongoClientDatabaseFactory(MongoClients.create(settings), properties.getDatabase());
  86. }
  87. }

创建对应文档类

具体代码参考单数据源(单节点)

操作示例

使用@Qualifier进行不同mongo的注入,具体代码如下

  1. @Resource
  2. @Qualifier(value = "primaryTemplate")
  3. private MongoTemplate primaryTemplate;
  4. @Resource
  5. @Qualifier(value = "secondaryTemplate")
  6. private MongoTemplate secondaryTemplate;
  7. @BeforeEach
  8. void beforeAll() {
  9. primaryTemplate.remove(new Query(), Student.class);
  10. secondaryTemplate.remove(new Query(), Student.class);
  11. }
  12. @Test
  13. void testInsert() {
  14. //1.创建主数据源对象
  15. Student student = new Student();
  16. student.setId(1);
  17. student.setName("主数据源数据");
  18. //2.主数据源保存
  19. primaryTemplate.insert(student);
  20. //3.创建从数据源对象
  21. student = new Student();
  22. student.setId(1);
  23. student.setName("从数据源数据");
  24. //4.从数据源保存
  25. secondaryTemplate.insert(student);
  26. }

3.单数据源(副本集)

添加配置

在yml下添加如下内容

  1. spring:
  2. data:
  3. mongodb:
  4. uri: mongodb://java_test:java_test@120.48.107.224:27017,120.48.107.224:27018/java_test?replicaSet=ftc&authSource=java_test&readPreference=secondaryPreferred&connectTimeoutMS=60000

链接参数介绍:

  1. replicaSet:集群名称
  2. authSource:当前用户名密码授权的数据库
  3. readPreference:读偏好,具体参考链接需要注意的是,mongo目前在事务中,只允许主节点读取数据,从节点读取数据会报错!!!!!!!!所以具体的参数配置要好好考虑一下
  4. connectTimeoutMS:链接超时毫秒

    其他步骤都与单数据源(单节点)一致

    4.多数据源(副本集)

    添加主数据源配置

    这里只做示例,副本集需要配置写关注,读关注,读偏好等参数 ```java package com.ftc.mongotest.config;

import cn.hutool.core.util.StrUtil; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClients; import com.mongodb.connection.ConnectionPoolSettings; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.mongodb.MongoTransactionManager; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit;

/**

  • @author: 冯铁城 [17615007230@163.com]
  • @date: 2022-07-29 15:44:02
  • @describe: mongo主数据源各种配置类 */ @Configuration @EnableMongoRepositories(basePackages = “com.ftc.mongotest”, mongoTemplateRef = “primaryTemplate”) public class PrimaryMongoTemplate {

    @Resource @Qualifier(“primaryMongoProperties”) private MongoConfigProperties primaryProperties;

    @Primary @Bean(name = “primaryTemplate”) public MongoTemplate primaryTemplate() {

    1. //1.获取primaryTemplate
    2. SimpleMongoClientDatabaseFactory primaryFactory = getFactory(this.primaryProperties);
    3. MongoTemplate primaryTemplate = new MongoTemplate(primaryFactory);
    4. //2.默认数据源监听处理
    5. String type = "_class";
    6. MongoConverter converter = primaryTemplate.getConverter();
    7. if (converter.getTypeMapper().isTypeKey(type)) {
    8. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
    9. }
    10. //3.返回
    11. return primaryTemplate;

    }

    @Bean(name = “primaryMongoTransactionManager”) public MongoTransactionManager primaryTransactionManager() {

    1. SimpleMongoClientDatabaseFactory factory = getFactory(this.primaryProperties);
    2. return new MongoTransactionManager(factory);

    }

    @Primary @Bean(name = “primaryGridFsTemplate”) public GridFsTemplate primaryGridFsTemplate() {

    1. SimpleMongoClientDatabaseFactory factory = getFactory(this.primaryProperties);
    2. MappingMongoConverter converter = new MappingMongoConverter(factory, new MongoMappingContext());
    3. return new GridFsTemplate(factory, converter);

    }

    @Primary @Bean(“primaryFactory”) public SimpleMongoClientDatabaseFactory getFactory(MongoConfigProperties properties) {

    1. //1.设置链接地址
    2. List<ServerAddress> hosts = new ArrayList<>();
    3. properties.getAddress().forEach(address -> {
    4. List<String> addressInfos = StrUtil.split(address, StrUtil.COLON);
    5. hosts.add(new ServerAddress(addressInfos.get(0), Integer.parseInt(addressInfos.get(1))));
    6. });
    7. //2.初始化连接池参数
    8. ConnectionPoolSettings poolSetting = ConnectionPoolSettings
    9. .builder()
    10. .maxWaitTime(10000, TimeUnit.MILLISECONDS)
    11. .build();
    12. //3.构造基础链接参数
    13. MongoClientSettings.Builder settingBuilder = MongoClientSettings
    14. .builder()
    15. .applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
    16. .applyToClusterSettings(builder -> builder.hosts(hosts))
    17. .readPreference(ReadPreference.secondaryPreferred());
    18. //4.初始链接参数以及连接池参数
    19. MongoClientSettings settings;
    20. //5.根据用户名是否为空判定是否鉴权
    21. if (StrUtil.isNotBlank(properties.getUsername())) {
    22. //6.添加授权参数
    23. MongoCredential credential = MongoCredential.createScramSha1Credential(
    24. properties.getUsername(), properties.getDatabase(), properties.getPassword().toCharArray()
    25. );
    26. //7.添加链接参数
    27. settings = settingBuilder.credential(credential).build();
    28. } else {
    29. //7.添加链接参数
    30. settings = settingBuilder.build();
    31. }
    32. //8.创建工厂返回
    33. return new SimpleMongoClientDatabaseFactory(MongoClients.create(settings), properties.getDatabase());

    } } ```

    添加备数据源配置

    这里只做示例,副本集需要配置写关注,读关注,读偏好等参数 ```java package com.ftc.mongotest.config;

import cn.hutool.core.util.StrUtil; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClients; import com.mongodb.connection.ConnectionPoolSettings; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.MongoTransactionManager; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit;

/**

  • @author: 冯铁城 [17615007230@163.com]
  • @date: 2022-07-29 15:44:02
  • @describe: mongo主数据源各种配置类 */ @Configuration @EnableMongoRepositories(basePackages = “com.ftc.mongotest”, mongoTemplateRef = “secondaryTemplate”) public class SecondaryMongoTemplate {

    @Resource @Qualifier(“secondaryMongoProperties”) private MongoConfigProperties secondaryProperties;

    @Bean(name = “secondaryTemplate”) public MongoTemplate secondaryTemplate() {

    1. //1.获取secondaryTemplate
    2. SimpleMongoClientDatabaseFactory secondaryFactory = getFactory(this.secondaryProperties);
    3. MongoTemplate secondaryTemplate = new MongoTemplate(secondaryFactory);
    4. //2.默认数据源监听处理
    5. String type = "_class";
    6. MongoConverter converter = secondaryTemplate.getConverter();
    7. if (converter.getTypeMapper().isTypeKey(type)) {
    8. ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
    9. }
    10. //3.返回
    11. return secondaryTemplate;

    }

    @Bean(name = “secondaryMongoTransactionManager”) public MongoTransactionManager secondaryTransactionManager() {

    1. SimpleMongoClientDatabaseFactory factory = getFactory(this.secondaryProperties);
    2. return new MongoTransactionManager(factory);

    }

    @Bean(name = “secondaryGridFsTemplate”) public GridFsTemplate secondaryGridFsTemplate() {

    1. SimpleMongoClientDatabaseFactory factory = getFactory(this.secondaryProperties);
    2. MappingMongoConverter converter = new MappingMongoConverter(factory, new MongoMappingContext());
    3. return new GridFsTemplate(factory, converter);

    }

    @Bean(“secondaryFactory”) public SimpleMongoClientDatabaseFactory getFactory(MongoConfigProperties properties) {

    1. //1.设置链接地址
    2. List<ServerAddress> hosts = new ArrayList<>();
    3. properties.getAddress().forEach(address -> {
    4. List<String> addressInfos = StrUtil.split(address, StrUtil.COLON);
    5. hosts.add(new ServerAddress(addressInfos.get(0), Integer.parseInt(addressInfos.get(1))));
    6. });
    7. //2.初始化连接池参数
    8. ConnectionPoolSettings poolSetting = ConnectionPoolSettings
    9. .builder()
    10. .maxWaitTime(10000, TimeUnit.MILLISECONDS)
    11. .build();
    12. //3.构造基础链接参数
    13. MongoClientSettings.Builder settingBuilder = MongoClientSettings
    14. .builder()
    15. .applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
    16. .applyToClusterSettings(builder -> builder.hosts(hosts))
    17. .readPreference(ReadPreference.secondaryPreferred());
    18. //4.初始链接参数以及连接池参数
    19. MongoClientSettings settings;
    20. //5.根据用户名是否为空判定是否鉴权
    21. if (StrUtil.isNotBlank(properties.getUsername())) {
    22. //6.添加授权参数
    23. MongoCredential credential = MongoCredential.createScramSha1Credential(
    24. properties.getUsername(), properties.getDatabase(), properties.getPassword().toCharArray()
    25. );
    26. //7.添加链接参数
    27. settings = settingBuilder.credential(credential).build();
    28. } else {
    29. //7.添加链接参数
    30. settings = settingBuilder.build();
    31. }
    32. //8.创建工厂返回
    33. return new SimpleMongoClientDatabaseFactory(MongoClients.create(settings), properties.getDatabase());

    } } ```

    其他步骤都与多数据源(单节点)一致