Fork me on GitHub

SpringBoot 集成mongodb(2)多数据源配置

github:https://github.com/xiaozhuanfeng/mongoProj

现MongoDB有两个数据库:

pom.xml:

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


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
  • Lombok - 是一个可以通过简单的注解形式来帮助我们简化消除一些必须有但显得很臃肿的Java代码的工具,通过使用对应的注解,可以在编译源码的时候生成对应的方法。简单试了以下这个工具还挺好玩的,加上注解我们就不用手动写 getter\setter、构建方式类似的代码了。

  • spring-boot-autoconfigure - 就是spring boot的自动化配置

注意这里Idea还可以设置Lombok插件:

https://blog.csdn.net/qq_37433657/article/details/83275051

配置文件:

#primary 数据源
mongodb.primary.host=192.168.0.102
mongodb.primary.port=27017
mongodb.primary.database=long

mongodb.secondary.host=192.168.0.102
mongodb.secondary.port=27017
mongodb.secondary.database=jianghu

1、配置两个数据库的数据源

package com.example.demo.config;

import lombok.Data;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
    private MongoProperties primary = new MongoProperties();
    private MongoProperties secondary = new MongoProperties();


    //安装Lombok插件,@Data
   /* public MongoProperties getPrimary() {
        return primary;
    }

    public MongoProperties getSecondary() {
        return secondary;
    }*/
}

2、配置不同包路径下使用不同的数据源

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = "com.example.demo.repository.primary", mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {
    protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}
package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableMongoRepositories(basePackages = "com.example.demo.repository.secondary",
        mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {
    protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}

3、读取对应的配置信息并且构造对应的MongoTemplate

package com.example.demo.config;

import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

@Configuration
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties;

    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }

    @Bean
    @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }

    @Bean
    @Primary
    public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
                mongo.getDatabase());
    }

    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
                mongo.getDatabase());
    }
}

4、新增实体类

对应DB=long的col集合

package com.example.demo.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "col")
public class Human {
    private String name;

    private int age;

    private String gender;

    @Override
    public String toString() {
        return "Human{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

对应DB=jianghu 的wuxia集合

package com.example.demo.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "wuxia")
public class Swordsman {

    private String name;

    private String age;

    private String skill;

    @Override
    public String toString() {
        return "Swordsman{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", skill='" + skill + '\'' +
                '}';
    }
}

5、对应的Repository

package com.example.demo.repository.primary;

import com.example.demo.dto.Human;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface PrimaryRepository extends MongoRepository<Human, String> {
}
package com.example.demo.repository.secondary;

import com.example.demo.dto.Swordsman;
import org.springframework.data.mongodb.repository.MongoRepository;

public interface SecondaryRepository extends MongoRepository<Swordsman, String> {
}

测试类:

package com.example.demo;

import com.example.demo.dto.Human;
import com.example.demo.dto.Swordsman;
import com.example.demo.repository.primary.PrimaryRepository;
import com.example.demo.repository.secondary.SecondaryRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MultipleMongoTest {

    @Autowired
    private PrimaryRepository primaryRepository;

    @Autowired
    private SecondaryRepository secondaryRepository;

    @Test
    public void test1(){
        List<Human> primaries = this.primaryRepository.findAll();
        for (Human primary : primaries) {
            System.out.println(primary.toString());
        }

        List<Swordsman> secondaries = this.secondaryRepository.findAll();

        for (Swordsman secondary : secondaries) {
            System.out.println(secondary.toString());
        }
    }
}

测试结果:

 

posted @ 2019-07-01 23:14  小传风  阅读(5529)  评论(0编辑  收藏  举报