springBoot集成MongoDB(集群配置)

基础配置
  • yml中mongo的配置
spring:
  data:
    mongodb:
      custom:
        database: admin
        hosts:
          - dds-u1.mongodb.rds.aliyuncs.com
          - dds-u2.mongodb.rds.aliyuncs.com
        ports:
          - 3717
          - 3717
        username: root
        password: 123456
        authenticationDatabase: admin
        maxConnections: 100
        minConnections: 20
        maxQueue: 10
获取配置资源

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;

@Component
@Validated
@Data
@ConfigurationProperties(prefix = "spring.data.mongodb.custom")
public class MongoDBProperties {
    @NotBlank
    private String database;

    @NotEmpty
    private List<String> hosts;

    @NotEmpty
    private List<Integer> ports;

    private String replicaSet;
    private String username;
    private String password;
    private String authenticationDatabase;
    private Integer minConnections;
    private Integer maxConnections;
    private Integer maxQueue;
}
注册配置信息

import com.mongodb.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class MongoConfig {

    private static final Logger log = LoggerFactory.getLogger(MongoConfig.class);

    private final
    MongoDBProperties mongoSettingsProperties;

    public MongoConfig(MongoDBProperties mongoSettingsProperties) {
        this.mongoSettingsProperties = mongoSettingsProperties;
    }


    @Bean
    MongoDbFactory mongoDbFactory() {
        //客户端配置(连接数、副本集群验证)
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(mongoSettingsProperties.getMaxConnections());
        builder.minConnectionsPerHost(mongoSettingsProperties.getMinConnections());
        builder.threadsAllowedToBlockForConnectionMultiplier(mongoSettingsProperties.getMaxQueue());
        builder.readPreference(ReadPreference.secondaryPreferred());

        if (mongoSettingsProperties.getReplicaSet() != null) {
            builder.requiredReplicaSetName(mongoSettingsProperties.getReplicaSet());
        }
        MongoClientOptions mongoClientOptions = builder.build();

        // MongoDB地址列表
        List<ServerAddress> serverAddresses = new ArrayList<>();
        for (String host : mongoSettingsProperties.getHosts()) {
            int index = mongoSettingsProperties.getHosts().indexOf(host);
            Integer port = mongoSettingsProperties.getPorts().get(index);

            ServerAddress serverAddress = new ServerAddress(host, port);
            serverAddresses.add(serverAddress);
        }
        log.info("MongoDB Server Addresses:[{}]", serverAddresses.toString());

        // 连接认证
        List<MongoCredential> mongoCredentialList = new ArrayList<>();
        if (mongoSettingsProperties.getUsername() != null) {
            mongoCredentialList.add(MongoCredential.createScramSha1Credential(
                    mongoSettingsProperties.getUsername(),
                    mongoSettingsProperties.getAuthenticationDatabase() != null ? mongoSettingsProperties.getAuthenticationDatabase() : mongoSettingsProperties.getDatabase(),
                    mongoSettingsProperties.getPassword().toCharArray()));
        }

        log.info("mongoDB CredentialList:[{}]", mongoCredentialList.toString());

        //创建客户端和Factory
        MongoClient mongoClient = new MongoClient(serverAddresses, mongoCredentialList, mongoClientOptions);

        return new SimpleMongoDbFactory(mongoClient, mongoSettingsProperties.getDatabase());
    }

    @Bean(name = "mongoTemplate")
    @Autowired
    public MongoTemplate getMongoTemplate(MongoDbFactory mongoDbFactory) {
        return new MongoTemplate(mongoDbFactory);

    }

}

去掉class字段

import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;

/**
 * 去除_class字段
 **/
@Configuration
public class MongoClassConfig implements ApplicationListener<ContextRefreshedEvent> {


    private final
    MongoTemplate mongoTemplate;

    public MongoClassConfig(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        MongoConverter mongoConverter = mongoTemplate.getConverter();

        if (mongoConverter.getTypeMapper().isTypeKey("_class")) {
            ((MappingMongoConverter) mongoConverter).setTypeMapper(new DefaultMongoTypeMapper(null));
        }
    }
}

你可能感兴趣的:(SpringBoot系列)