spring boot 重写MongoDbFacotry

第一步:添加依赖

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath />
    </parent>
  
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

    </dependencies>

第二步:在配置文件中添加mongodb属性


mongodb.host=
mongodb.database=
mongodb.username=
mongodb.password=
mongodb.port=
mongo.replica-set=reolicaName
mongo.options.min-connections-per-host=20
mongo.options.max-connections-per-host=20
mongo.options.threads-allowed-to-block-for-connection-multiplier=5
mongo.options.server-selection-timeout=30000
mongo.options.max-wait-time=120000
mongo.options.max-connection-idel-time=0
mongo.options.max-connection-life-time=0
mongo.options.connect-timeout=10000
mongo.options.socket-timeout=0
mongo.options.socket-keep-alive=false
mongo.options.ssl-enabled=false
mongo.options.ssl-invalid-host-name-allowed=false
mongo.options.always-use-m-beans=false
mongo.options.heartbeat-socket-timeout=20000
mongo.options.heartbeat-connect-timeout=20000
mongo.options.min-heartbeat-frequency=500
mongo.options.heartbeat-frequency=10000
mongo.options.local-threshold=15

第三步:把配置文件映射成jave bean

@Component
@Validated 
@PropertySource(value = "classpath:application.properties")
@ConfigurationProperties(prefix = "mongodb")
public class MongoSettingsProperties {

    protected String host;
    protected int port;
    protected String username;
    protected String password;
    @NotBlank
    protected String database;

    private String replicaSet;
    private Integer minConnectionsPerHost = 0;
    private Integer maxConnectionsPerHost = 100;
    private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
    private Integer serverSelectionTimeout = 30000;
    private Integer maxWaitTime = 120000;
    private Integer maxConnectionIdleTime = 0;
    private Integer maxConnectionLifeTime = 0;
    private Integer connectTimeout = 10000;
    private Integer socketTimeout = 0;
    private Boolean socketKeepAlive = false;
    private Boolean sslEnabled = false;
    private Boolean sslInvalidHostNameAllowed = false;
    private Boolean alwaysUseMBeans = false;
    private Integer heartbeatFrequency = 10000;
    private Integer minHeartbeatFrequency = 500;
    private Integer heartbeatConnectTimeout = 20000;
    private Integer heartbeatSocketTimeout = 20000;
    private Integer localThreshold = 15;

----get、set方法省略---- }

第四步:重置MongoDbFactory

@Configuration
public class MongoConfig {

    // 覆盖默认的MongoDbFacotry
    @Bean
    @Autowired
    public MongoDbFactory mongoDbFactory(MongoSettingsProperties properties) {
        //客户端配置(连接数,副本集群验证)
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(properties.getMaxConnectionsPerHost());
        builder.minConnectionsPerHost(properties.getMinConnectionsPerHost());
        if (properties.getReplicaSet() != null) {
            builder.requiredReplicaSetName(properties.getReplicaSet());
        }                    
        builder.threadsAllowedToBlockForConnectionMultiplier(
                properties.getThreadsAllowedToBlockForConnectionMultiplier());
        builder.serverSelectionTimeout(properties.getServerSelectionTimeout());
        builder.maxWaitTime(properties.getMaxWaitTime());
        builder.maxConnectionIdleTime(properties.getMaxConnectionIdleTime());
        builder.maxConnectionLifeTime(properties.getMaxConnectionLifeTime());
        builder.connectTimeout(properties.getConnectTimeout());
        builder.socketTimeout(properties.getSocketTimeout());
        builder.socketKeepAlive(properties.getSocketKeepAlive());
        builder.sslEnabled(properties.getSslEnabled());
        builder.sslInvalidHostNameAllowed(properties.getSslInvalidHostNameAllowed());
        builder.alwaysUseMBeans(properties.getAlwaysUseMBeans());
        builder.heartbeatFrequency(properties.getHeartbeatFrequency());
        builder.minHeartbeatFrequency(properties.getMinHeartbeatFrequency());
        builder.heartbeatConnectTimeout(properties.getHeartbeatConnectTimeout());
        builder.heartbeatSocketTimeout(properties.getHeartbeatSocketTimeout());
        builder.localThreshold(properties.getLocalThreshold());
        MongoClientOptions mongoClientOptions = builder.build();

        String host = properties.getHost();
        Integer port = properties.getPort();
        ServerAddress serverAddress = new ServerAddress(host, port);
        
        // 连接认证
        MongoCredential mongoCredential = MongoCredential.createScramSha1Credential(properties.getUsername(),
                properties.getDatabase(), properties.getPassword().toCharArray());
        
        // 创建客户端和Factory
        MongoClient mongoClient = new MongoClient(serverAddress, mongoCredential, mongoClientOptions);
        MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, properties.getDatabase());

        return mongoDbFactory;
    }
}

第五步:使用MongoTemplate

@Repository
public class AllWindFieldCodeDaoImpl implements AllWindFieldCodeDao {

    @Autowired
    private MongoTemplate mongoTemplate;
原文地址:https://www.cnblogs.com/mcahkf/p/9590880.html