Method Steps for springboot mongodb Multiple Data Source Configuration

  • 2021-07-24 10:51:43
  • OfStack

In daily work, we may need to connect to multiple MongoDB data sources, such as user repository user and log repository log. In this chapter, we will document the steps to connect multiple data sources, taking two data sources as examples and multiple data sources as analogies.

1. The dependency of introducing mongodb into pom. xml


<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>

Lombok-is a tool that simplifies and eliminates the necessary but bloated Java code with simple annotations that generate methods when compiling the source code. It's fun to simply try the following tool. With annotations, we don't have to write getter\ setter manually, and build code in a similar way.

2. yml configuration:


mongodb:
 primary:
  host: 192.168.9.60
  port: 20000
  database: test
 secondary:
  host: 192.168.9.60
  port: 20000
  database: test1

3. Configure the data sources of the two libraries:


@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {

  private MongoProperties primary = new MongoProperties();
  private MongoProperties secondary = new MongoProperties();
}

3.1) The first library encapsulation:


@Configuration
@EnableMongoRepositories(basePackages = "com.neo.model.repository.primary",
    mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {

  protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}

3.2) The second library encapsulation:


@Configuration
@EnableMongoRepositories(basePackages = "com.neo.model.repository.secondary",
    mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {

  protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}

3.3) mongoTemplate:


@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. Create repository corresponding to two libraries:


@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "first_mongo")
public class PrimaryMongoObject {

  @Id
  private String id;

  private String value;

  @Override
  public String toString() {
    return "PrimaryMongoObject{" + "id='" + id + '\'' + ", value='" + value + '\''
        + '}';
  }
}

public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> {
}

Test:


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

  @Autowired
  private PrimaryRepository primaryRepository;

  @Autowired
  private SecondaryRepository secondaryRepository;

  @Test
  public void TestSave() {

    System.out.println("************************************************************");
    System.out.println(" Test commencement ");
    System.out.println("************************************************************");

    this.primaryRepository
        .save(new PrimaryMongoObject(null, " No. 1 1 Objects of a library "));

    this.secondaryRepository
        .save(new SecondaryMongoObject(null, " No. 1 2 Objects of a library "));

    List<PrimaryMongoObject> primaries = this.primaryRepository.findAll();
    for (PrimaryMongoObject primary : primaries) {
      System.out.println(primary.toString());
    }

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

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

    System.out.println("************************************************************");
    System.out.println(" Test completion ");
    System.out.println("************************************************************");
  }

}


Related articles: