美文网首页
mongo配置多数据源

mongo配置多数据源

作者: 谁在烽烟彼岸 | 来源:发表于2019-09-27 14:40 被阅读0次

    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);
        }
    
    }
    

    相关文章

      网友评论

          本文标题:mongo配置多数据源

          本文链接:https://www.haomeiwen.com/subject/cxmkuctx.html