springboot mongodb 多数据源

1.配置抽象类

import com.mongodb.MongoClientURI;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

public abstract class AbstractMongoConfig{

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    protected String uri;

    public MongoDbFactory mongoDbFactory(){

        return new SimpleMongoClientDbFactory(uri);
    }
    public abstract MongoTemplate getMongoTemplate();

}

2.主数据源,也是默认数据源,配置类

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

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

3.第二个数据源配置类,注意 @ConfigurationProperties(prefix=“spring.data.mongodb.second”) 中的second与配置文件的参数名保持一致


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

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

4.配置文件配置参数

spring:
  data:
    mongodb:
      uri: mongodb://账号:密码@ip:端口,ip2:端口/数据库名1?connect=replicaSet&replicaSet=replicaSet&slaveOk=true&authSource=admin
      second:
        uri: mongodb://账号:密码@ip:端口,ip2:端口/数据库名2?connect=replicaSet&replicaSet=replicaSet&slaveOk=true&authSource=admin

5.在代码中使用

//注册第一个数据库连接
    @Autowired
    MongoTemplate mongoTemplate;

//注册第二个数据库连接
    @Autowired
    @Qualifier(name = "secondMongoTemplate")
    private MongoTemplate secondMongoTemplate;

6.pom依赖

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

你可能感兴趣的:(mongodb,spring,boot,数据库)