mongo配置多数据源

mongodb配置多个数据源
直接上代码

package com.kmind;

import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;


/**
 * @author lpf
 * @Description mongoDb的多数据库
 * @CreateAt 2018/6/15
 * @ModifyAt
 * @ModifyBy
 */
@Configuration
public class DatabaseConfig {
    @Value("${myDB}")
    private String myDB;
    @Value("${database2}")
    private String database2;
    @Value("${my.data.mongodb.uri}")
    private String uri;


    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory());
    }

    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(secondaryFactory());
    }


    @Bean
    @Primary
    public MongoDbFactory primaryFactory() throws Exception {
        MongoClientURI connectionString = new MongoClientURI("mongodb://root:password@" + uri + "/" + myDB + "?authSource=admin&authMechanism=SCRAM-SHA-1");
        return new SimpleMongoDbFactory(connectionString);
    }

    @Bean
    public MongoDbFactory secondaryFactory() throws Exception {
        MongoClientURI connectionString = new MongoClientURI("mongodb://root:password@" + uri + "/" + database2 + "?authSource=admin&authMechanism=SCRAM-SHA-1");
        return new SimpleMongoDbFactory(connectionString);
    }

}

推荐阅读更多精彩内容