Springboot integrated mongodb

1. Introduce dependencies
1.1 Maven

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

2. yml configuration file

data:
  mongodb:
    #Basic link parameters
    # Linked libraries
    database: mongodb
    # username
    username: mongodb
    # password
    password:mongodb
    # IP and port (host:port), such as 127.0.0.1:27017. Cluster mode is separated by, such as host1:port1,host2:port2
    address: 192.168.1.1:3717,192.168.1.2:3717
    # Set up the authentication database, if any
    authenticationDatabase:
    # Client connection pool parameters
    clientName: ${spring.application.name}
    # TCP (socket) connection timeout, milliseconds
    connectionTimeoutMs: 5000
    # TCP (socket) connection idle time, milliseconds
    maxConnectionIdleTimeMs: 60000
    #How long a TCP (socket) connection can be used at most, milliseconds
    maxConnectionLifeTimeMs: 300000
    #TCP (socket) read timeout, milliseconds
    readTimeoutMs: 15000
    #Heartbeat detection sending frequency, milliseconds
    heartbeatFrequencyMs: 20000
    #The maximum number of connections allowed by the thread pool
    connectionsPerHost: 100
    #Minimum number of connections maintained when the thread pool is idle
    minConnectionsPerHost: 20

3. MongoConfig configuration class
Partially configurable, you can view the source code of the AbstractMongoClientConfiguration class

@Configuration
@EnableConfigurationProperties(MongoConfig.MongoClientOptionProperties.class)
@Slf4j
public class MongoConfig {
 
    /**
     * converter
     * MappingMongoConverter can customize the mongo converter, mainly customizing some operations when accessing mongo data, such as mappingConverter.setTypeMapper(new
     * The DefaultMongoTypeMapper(null)) method will remove the _class field in the mongo data.
     *
     * @param factory mongo factory
     * @param context context
     * @param beanFactory custom converter
     * @return converter object
     */
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
 
        }
 
        // _class to field mongo is not required for saving
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
 
        return mappingConverter;
    }
 
    @Bean
    public MongoTypeMapper defaultMongoTypeMapper() {
        return new DefaultMongoTypeMapper(null);
    }
 
    /**
     * This Bean can also be defined without explicit definition. If we do not explicitly define it to generate a MongoTemplate instance,
     * SpringBoot uses our configured MongoDbFactory to generate a MongoTemplate in the configuration class.
     * Then we can @Autowired directly in the project code. Because for generating MongoTemplate
     * The MongoDbFactory is generated by ourselves in the MongoConfig configuration class, so our customized connection pool parameters will also take effect.
     *
     * @param mongoDbFactory mongo factory
     * @param converter converter
     * @return MongoTemplate instance
     */
    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, MappingMongoConverter converter) {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
        //Set the priority of reading from the library
        mongoTemplate.setReadPreference(ReadPreference.secondaryPreferred());
        return mongoTemplate;
    }
 
    /**
     * Custom mongo connection pool
     *
     * @param properties property configuration class
     * @return MongoDbFactory object
     */
    @Bean
    public MongoDatabaseFactory mongoDbFactory(MongoClientOptionProperties properties) {
        //Create client parameters
        MongoClientSettings mongoClientOptions = mongoClientSettings(properties);
 
        // Mongo Client
        MongoDriverInformation info = MongoDriverInformation.builder().build();
 
        MongoClient mongoClient = new MongoClientImpl(mongoClientOptions, info);
 
        return new SimpleMongoClientDatabaseFactory(mongoClient, properties.database);
    }
 
    @Bean
    public MongoClientSettings mongoClientSettings(MongoClientOptionProperties properties) {
        //Create certification
        MongoCredential mongoCredential = getCredential(properties);
        // Parse and obtain the mongo service address
        List<ServerAddress> serverAddressList = getServerAddress(properties.getAddress());
 
        return MongoClientSettings.builder()
                //#Identification of the client, used to locate the source of the request, etc., usually the program name is used
                .applicationName(properties.clientName)
                //Configure IP address
                .applyToClusterSettings(i -> i.hosts(serverAddressList))
                //Configure authentication
                .credential(mongoCredential)
 
                .applyToSocketSettings(i -> i
                        //TCP (socket) read timeout, milliseconds
                        .readTimeout(properties.readTimeoutMs, TimeUnit.MILLISECONDS)
                        //TCP (socket) connection timeout, milliseconds
                        .connectTimeout(properties.connectionTimeoutMs, TimeUnit.MILLISECONDS))
 
                .applyToConnectionPoolSettings(i -> i
                        //TCP (socket) connection idle time, milliseconds
                        .maxConnectionIdleTime(properties.maxConnectionIdleTimeMs, TimeUnit.MILLISECONDS)
                        //How long can the TCP (socket) connection be used at most, milliseconds?
                        .maxConnectionLifeTime(properties.maxConnectionIdleTimeMs, TimeUnit.MILLISECONDS)
                        //The maximum length of time for the client to block and wait when there is no available connection in the connection pool, milliseconds
                        .maxWaitTime(properties.maxWaitTimeMs, TimeUnit.MILLISECONDS)
                        .maxSize(properties.connectionsPerHost)
                        .minSize(properties.minConnectionsPerHost))
 
                .applyToServerSettings(i -> i
                        .heartbeatFrequency(properties.heartbeatFrequencyMs, TimeUnit.MILLISECONDS)
                        .minHeartbeatFrequency(properties.minHeartbeatFrequencyMs, TimeUnit.MILLISECONDS))
 
 
                .build();
    }
 
    /**
     * Create certification
     *
     * @param properties property configuration class
     * @return authentication object
     */
    private MongoCredential getCredential(MongoClientOptionProperties properties) {
        if (!StringUtils.isEmpty(properties.getUsername()) & amp; & amp; !StringUtils.isEmpty(properties.getPassword())) {
            // If there is no dedicated authentication database, take the current database
            String database = StringUtils.isEmpty(properties.getAuthenticationDatabase()) ?
                    properties.getDatabase() : properties.getAuthenticationDatabase();
            return MongoCredential.createCredential(properties.getUsername(), database,
                    properties.getPassword().toCharArray());
        }
        return null;
    }
 
    /**
     * Get the database service address
     *
     * @param mongoAddress address string
     * @return service address array
     */
    private List<ServerAddress> getServerAddress(String mongoAddress) {
        String[] mongoAddressArray = mongoAddress.trim().split(",");
        List<ServerAddress> serverAddressList = new ArrayList<>(4);
        for (String address : mongoAddressArray) {
            String[] hostAndPort = address.split(":");
            serverAddressList.add(new ServerAddress(hostAndPort[0], Integer.parseInt(hostAndPort[1])));
        }
        return serverAddressList;
    }
 
    @Setter
    @Getter
    @Accessors(chain = true)
    @ConfigurationProperties(prefix = "data.mongodb")
    public class MongoClientOptionProperties {
        /**
         *Basic connection parameters
         */
        //The database to connect to
        @NotEmpty
        private String database;
        // username
        private String username;
        // password
        private String password;
        // IP and port (host:port), such as 127.0.0.1:27017. Cluster mode is separated by, such as host1:port1,host2:port2
        //@NotEmpty
        private String address;
        // Set up the authentication database, if any
        private String authenticationDatabase;
 
        /**
         * Client connection pool parameters
         */
        @NotEmpty
        private String clientName; // Identification of the client, used to locate the source of the request, etc., usually the program name is used
        @Min(value = 1)
        private int connectionTimeoutMs; // TCP (socket) connection timeout, milliseconds
        @Min(value = 1)
        private int maxConnectionIdleTimeMs; // TCP (socket) connection idle time, milliseconds
        @Min(value = 1)
        private int maxConnectionLifeTimeMs; //The maximum length of time a TCP (socket) connection can be used, milliseconds
        @Min(value = 1)
        private int readTimeoutMs; // TCP (socket) read timeout, milliseconds
        @Min(value = 1)
        private int maxWaitTimeMs; // The maximum length of time the client blocks and waits when there is no available connection in the connection pool, milliseconds
        @Min(value = 2000)
        private int heartbeatFrequencyMs; // Heartbeat detection sending frequency, milliseconds
        @Min(value = 300)
        private int minHeartbeatFrequencyMs; // Minimum heartbeat detection sending frequency, milliseconds
        @Min(value = 200)
        private int heartbeatConnectionTimeoutMs; // Heartbeat detection connection timeout, milliseconds
        @Min(value = 200)
        private int heartbeatReadTimeoutMs; // Heartbeat detection read timeout, milliseconds
        @Min(value = 1)
        private int connectionsPerHost; // The maximum number of connections allowed by the thread pool
        @Min(value = 1)
        private int minConnectionsPerHost; // The minimum number of connections maintained when the thread pool is idle
        @Min(value = 1)
        // Calculate the multiplier for how many threads are allowed to block and wait, algorithm: threadsAllowedToBlockForConnectionMultiplier*maxConnectionsPerHost
        private int threadsAllowedToBlockForConnectionMultiplier;