如何在spring boot中使用多个mongodb数据库?

时间:2022-09-23 08:09:43

I use spring boot to operate mongodb, and in my application.properties is spring.data.mongodb.uri=mongodb://username:password@hostIp:27017/database1 and I add jar is spring-boot-starter-data-mongodb, but now there are two database in my mongodb, and how can I add another database in my spring boot, and how can I distinguish them when I use different database?

我使用spring boot来操作mongodb,在我的application.properties中是spring.data.mongodb.uri = mongodb:// username:password @ hostIp:27017 / database1我添加jar是spring-boot-starter-data-mongodb ,但现在我的mongodb中有两个数据库,如何在我的spring boot中添加另一个数据库,当我使用不同的数据库时如何区分它们呢?

1 个解决方案

#1


0  

Yes, You can configure 2 databases in single spring-boot application. You have to add two database properties in single application.yml file.

是的,您可以在单个spring-boot应用程序中配置2个数据库。您必须在单个application.yml文件中添加两个数据库属性。

#application.yml
        spring:
          data:
            mongodb:
              database: database_one
              uri: mongodb://root:root@172.0.0.1:27017/database_one
    # username : root, Password : root

        secondary:
          mongodb:
            database: database_two
            uri: mongodb://root:password@172.0.0.1:27017/database_two
    # username : root, Password : password

Then you have to add two database configuration files for spring and read these two properties in each file. For first database configuration file just add @Primary annotation for primary database properties. You can combine these two files in single as per your requirement.

然后,您必须为spring添加两个数据库配置文件,并在每个文件中读取这两个属性。对于第一个数据库配置文件,只需为主数据库属性添加@Primary注释。您可以根据需要将这两个文件合并为一个。

@Configuration
public class DatabaseConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConfiguration.class);

    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;

    @Value("${spring.data.mongodb.database}")
    private String mongoDbName;

    @Primary
    @Bean
    public MongoTemplate mongoTemplate() {    
        LOGGER.debug(" Instantiating MongoDbFactory ");
        SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient(), mongoDbName);
            return new MongoTemplate(mongoDbFactory);
        }

    @Primary
    @Bean
    public MongoClient mongoClient() {
        return new MongoClient(mongoClientURI());
    }

    @Primary
    @Bean
    public MongoClientURI mongoClientURI() {
        LOGGER.debug(" creating connection with mongodb with uri [{}] ", mongoUri);
        return new MongoClientURI(mongoUri);
    }

}


# Second database configuration file.

@Configuration
public class SecondaryDatabaseConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecondaryDatabaseConfiguration.class);

    @Value("${secondary.mongodb.uri}")
    private String mongoUri;

    @Value("${secondary.mongodb.database}")
    private String mongoDbName ;

    @Bean(name = "mongoTemplateSecond")
    public MongoTemplate mongoTemplateSecondary() {
        LOGGER.debug(" Instantiating MongoDbFactory ");
        SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClientSecondary(), mongoDbName);
        return new MongoTemplate(mongoDbFactory);
    }

    @Bean
    public MongoClient mongoClientSecondary() {
        return new MongoClient(mongoClientURISecondary());
    }

    @Bean
    public MongoClientURI mongoClientURISecondary() {
        LOGGER.debug(" creating connection with mongodb with uri [{}] ", mongoUri);
        return new MongoClientURI(mongoUri);
    }
}

Then use @Qualifier annotation in your implementation class and pass bean name if you want to fetch from secondary database and for primary database you can directly Autowire.
@Qualifier annotation is used to differentiate beans of the same type.

然后在实现类中使用@Qualifier注释,如果要从辅助数据库中获取,则传递bean名称;对于主数据库,可以直接使用Autowire。 @Qualifier注释用于区分相同类型的bean。

    @Component
public class RepositoryImpl{

    @Qualifier(value = "mongoTemplateSecond")
    @Autowired
    MongoTemplate mongoTemplateSecond;   // for secondary database


    @Autowired
    private MongoTemplate mongoTemplate; // for primary database 


    public List<BasicDBObject> findRecordsInSecondary(Query query){
        List<BasicDBObject> basicDBObjects = mongoTemplateSecond.find(query, BasicDBObject.class, YOUR_COLLECTION_NAME);
        return basicDBObjects;
    }


    public List<BasicDBObject> findRecordsInPrimary(Query query){
        List<BasicDBObject> basicDBObjects = mongoTemplate.find(query, BasicDBObject.class, YOUR_COLLECTION_NAME);
        return basicDBObjects;
    }
}

#1


0  

Yes, You can configure 2 databases in single spring-boot application. You have to add two database properties in single application.yml file.

是的,您可以在单个spring-boot应用程序中配置2个数据库。您必须在单个application.yml文件中添加两个数据库属性。

#application.yml
        spring:
          data:
            mongodb:
              database: database_one
              uri: mongodb://root:root@172.0.0.1:27017/database_one
    # username : root, Password : root

        secondary:
          mongodb:
            database: database_two
            uri: mongodb://root:password@172.0.0.1:27017/database_two
    # username : root, Password : password

Then you have to add two database configuration files for spring and read these two properties in each file. For first database configuration file just add @Primary annotation for primary database properties. You can combine these two files in single as per your requirement.

然后,您必须为spring添加两个数据库配置文件,并在每个文件中读取这两个属性。对于第一个数据库配置文件,只需为主数据库属性添加@Primary注释。您可以根据需要将这两个文件合并为一个。

@Configuration
public class DatabaseConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseConfiguration.class);

    @Value("${spring.data.mongodb.uri}")
    private String mongoUri;

    @Value("${spring.data.mongodb.database}")
    private String mongoDbName;

    @Primary
    @Bean
    public MongoTemplate mongoTemplate() {    
        LOGGER.debug(" Instantiating MongoDbFactory ");
        SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient(), mongoDbName);
            return new MongoTemplate(mongoDbFactory);
        }

    @Primary
    @Bean
    public MongoClient mongoClient() {
        return new MongoClient(mongoClientURI());
    }

    @Primary
    @Bean
    public MongoClientURI mongoClientURI() {
        LOGGER.debug(" creating connection with mongodb with uri [{}] ", mongoUri);
        return new MongoClientURI(mongoUri);
    }

}


# Second database configuration file.

@Configuration
public class SecondaryDatabaseConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecondaryDatabaseConfiguration.class);

    @Value("${secondary.mongodb.uri}")
    private String mongoUri;

    @Value("${secondary.mongodb.database}")
    private String mongoDbName ;

    @Bean(name = "mongoTemplateSecond")
    public MongoTemplate mongoTemplateSecondary() {
        LOGGER.debug(" Instantiating MongoDbFactory ");
        SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClientSecondary(), mongoDbName);
        return new MongoTemplate(mongoDbFactory);
    }

    @Bean
    public MongoClient mongoClientSecondary() {
        return new MongoClient(mongoClientURISecondary());
    }

    @Bean
    public MongoClientURI mongoClientURISecondary() {
        LOGGER.debug(" creating connection with mongodb with uri [{}] ", mongoUri);
        return new MongoClientURI(mongoUri);
    }
}

Then use @Qualifier annotation in your implementation class and pass bean name if you want to fetch from secondary database and for primary database you can directly Autowire.
@Qualifier annotation is used to differentiate beans of the same type.

然后在实现类中使用@Qualifier注释,如果要从辅助数据库中获取,则传递bean名称;对于主数据库,可以直接使用Autowire。 @Qualifier注释用于区分相同类型的bean。

    @Component
public class RepositoryImpl{

    @Qualifier(value = "mongoTemplateSecond")
    @Autowired
    MongoTemplate mongoTemplateSecond;   // for secondary database


    @Autowired
    private MongoTemplate mongoTemplate; // for primary database 


    public List<BasicDBObject> findRecordsInSecondary(Query query){
        List<BasicDBObject> basicDBObjects = mongoTemplateSecond.find(query, BasicDBObject.class, YOUR_COLLECTION_NAME);
        return basicDBObjects;
    }


    public List<BasicDBObject> findRecordsInPrimary(Query query){
        List<BasicDBObject> basicDBObjects = mongoTemplate.find(query, BasicDBObject.class, YOUR_COLLECTION_NAME);
        return basicDBObjects;
    }
}