【开发心得】spring-data-mongo多数据源配置

环境:

SpringBoot2.5.7

SpringBootStarterDataMongo(SpringDataMongo3.2.7)

请确认您的环境,因为spingData系列迭代很快,并且一些接口,类和实现都会变更,需要针对性修改。

pom.xml 这里只贴mongo相关,boot本身的自行引入。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.mongodb</groupId>
                    <artifactId>bson</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.mongodb</groupId>
                    <artifactId>mongodb-driver-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>bson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-core</artifactId>
        </dependency>

配置类:

PrimaryConfig

package com.martin.myutils.config;

import com.martin.myutils.dao.mongo.mapper.DocumentDataRepository;
import com.martin.myutils.dao.mongo.mapper.ProgramDocumentRepository;
import com.martin.myutils.dao.mongo.mapper.SmartDocumentDataRepository;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import static java.util.Collections.singletonList;

/**
 * @Author: martin
 * @Date: 2023-02-06 10:30
 * @Description:
 */
@Primary
@Configuration
@EnableMongoRepositories(basePackageClasses = {DocumentDataRepository.class,
        ProgramDocumentRepository.class, SmartDocumentDataRepository.class}, mongoTemplateRef = "primaryMongoTemplate")
@EnableConfigurationProperties
public class PrimaryConfig {

    @Primary
    @Bean(name = "primaryProperties")
    @ConfigurationProperties(prefix = "mongodb.primary")
    public MongoProperties primaryProperties() {
        return new MongoProperties();
    }

    @Bean(name = "primaryMongoClient")
    public MongoClient mongoClient(@Qualifier("primaryProperties") MongoProperties mongoProperties) {

        MongoCredential credential = MongoCredential
                .createCredential(mongoProperties.getUsername(), mongoProperties.getAuthenticationDatabase(), mongoProperties.getPassword());

        return MongoClients.create(MongoClientSettings.builder()
                .applyToClusterSettings(builder -> builder
                        .hosts(singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort()))))
                .credential(credential)
                .build());
    }

    @Primary
    @Bean(name = "primaryMongoDBFactory")
    public MongoDatabaseFactory mongoDatabaseFactory(
            @Qualifier("primaryMongoClient") MongoClient mongoClient,
            @Qualifier("primaryProperties") MongoProperties mongoProperties) {
        return new SimpleMongoClientDatabaseFactory(mongoClient, mongoProperties.getDatabase());
    }

    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate mongoTemplate(@Qualifier("primaryMongoDBFactory") MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}
package com.martin.myutils.config;

import com.martin.myutils.dao.mongo.mapper.MetaDataRepository;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import static java.util.Collections.singletonList;

/**
 * @Author: martin
 * @Date: 2023-02-06 10:30
 * @Description:
 */
@Configuration
@EnableMongoRepositories(basePackageClasses = MetaDataRepository.class, mongoTemplateRef = "secondaryMongoTemplate")
@EnableConfigurationProperties
public class SecondaryConfig {

    @Bean(name = "secondaryProperties")
    @ConfigurationProperties(prefix = "mongodb.secondary")
    public MongoProperties secondaryProperties() {
        return new MongoProperties();
    }

    @Bean(name = "secondaryMongoClient")
    public MongoClient mongoClient(@Qualifier("secondaryProperties") MongoProperties mongoProperties) {

        MongoCredential credential = MongoCredential
                .createCredential(mongoProperties.getUsername(), mongoProperties.getAuthenticationDatabase(), mongoProperties.getPassword());

        return MongoClients.create(MongoClientSettings.builder()
                .applyToClusterSettings(builder -> builder
                        .hosts(singletonList(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort()))))
                .credential(credential)
                .build());
    }

    @Bean(name = "secondaryMongoDBFactory")
    public MongoDatabaseFactory mongoDatabaseFactory(
            @Qualifier("secondaryMongoClient") MongoClient mongoClient,
            @Qualifier("secondaryProperties") MongoProperties mongoProperties) {
        return new SimpleMongoClientDatabaseFactory(mongoClient, mongoProperties.getDatabase());
    }

    @Bean(name = "secondaryMongoTemplate")
    public MongoTemplate mongoTemplate(@Qualifier("secondaryMongoDBFactory") MongoDatabaseFactory mongoDatabaseFactory) {
        return new MongoTemplate(mongoDatabaseFactory);
    }
}

两份配置基本一致,主要区别一个是primaryxxx,一个是secondaryxxx,同时primaryConfig中,需要对MongoProperties,MongoDatabaseFactory,MongoTemplate 增加@Primary,确保单例,同时确保application.yml中不要出现spring.mongo,否则会报错多个Bean问题

Parameter 1 of method mongoMappingContext in org.springframework.boot.autoco

使用:

package com.martin.myutils.dao.mongo.mapper.impl;

import com.martin.myutils.dao.mongo.entity.Meta;
import com.martin.myutils.dao.mongo.mapper.MetaDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: martin
 * @Date: 2023-02-03 09:23
 * @Description:
 */
@Slf4j
@Service
public class MetaDataRepositoryImpl implements MetaDataRepository {
    @Qualifier(value = "secondaryMongoTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Meta> find(Query query) {
        return mongoTemplate.find(query, Meta.class);
    }
}

需要引入mongoTemplate的时候指定要注入的Bean

结语: 使用Mongo多数据库的情况很少,所以一般没有样例,或者样例很老,这里特此写一篇文档,当做笔记,也为后来人开路。

posted @ 2023-02-06 11:24  虹梦未来  阅读(120)  评论(0编辑  收藏  举报  来源