mongodb多數據源配置


 

引入spring-data 依賴

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

 

數據源配置,多個數據源

spring:
    mongodb:
primary: uri: mongodb://username1:password1@localost:27018/db1
secondary: uri:
mongodb://username2:password2@localost:27018/db2
    thirdly: 
     uri:
mongodb://username3:password3@localost:27018/db3
 
        

 

配置類

@Data
public abstract class AbstractMongoConfig {

    private String uri;

    public abstract MongoTemplate mongoTemplate();

    public MongoDbFactory mongoDbFactory(){
        MongoClientURI mongoclienturi = new MongoClientURI(uri);
        return new SimpleMongoDbFactory(mongoclienturi);
    }

}

 

@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.primary")
public class PrimaryMongoConfig extends AbstractMongoConfig  {

    @Primary //默認會注入此數據源的Template
    @Override
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate mongoTemplate(){
        return new MongoTemplate(mongoDbFactory());
    }
}

 

@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.secondary")
public class SecondaryMongoConfig extends  AbstractMongoConfig{

    @Override
    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate mongoTemplate(){
        return new MongoTemplate(mongoDbFactory());
    }
}

 

@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.thirdly")
public class ThirdlyMongoConfig extends  AbstractMongoConfig{

    @Override
    @Bean(name = "thirdlyMongoTemplate")
    public MongoTemplate mongoTemplate(){
        return new MongoTemplate(mongoDbFactory());
    }
}

 

注入MongoTemplate 進行增刪改查

  @Autowired
    private MongoTemplate mongoTemplate;

   @Autowired
    @Qualifier("secondaryMongoTemplate")
    private MongoTemplate template2;

    @Autowired
    @Qualifier("thirdlyMongoTemplate")
    private MongoTemplate template3;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM