Go教程

mongodb多数据源配置

本文主要是介绍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;

 

这篇关于mongodb多数据源配置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!