본문 바로가기
IT/Spring

Spring Mongo Database (Multi Database)

by 민쌍 2021. 2. 7.

Mongo Database LifeCycle

MongoClient → SimpleMongoClientDatabaseFactory → MongoTemplate → MongoRepositories

MongoTemplate

  • Where 조건

    • Query, Criteria class 사용

      //                    where 조건 추가 방법 
            Query query = new Query(Criteria.where("creationDate").is("20201230"));
            Query query2 = new Query(Criteria.where("_id").is(new ObjectId("5ff378d01771886191254abb")));
      
      //        Json String return
            String s  = mongoArchiveTemplate.findOne(query, String.class, "krxListedStocks");
      

MongoRepository

  • ORM JPA 방식과 사용방법 동일

  • findby-, save, update, delete 등 메소드 사용 가능

  • MongoRepository는 MongoTemplate을 사용

Multi Database 사용할 경우,

MultipleDatabaseConfig.java

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
public class MultipleDatabaseConfig {

    @Value("${spring.data.mongodb.archive.host}")
    String archiveHostName;
    @Value("${spring.data.mongodb.archive.database}")
    String archiveDatabaseName;

    @Bean
    @Primary
    public SimpleMongoClientDatabaseFactory *archiveMongoDbFactory*(){
        return new SimpleMongoClientDatabaseFactory(**archiveMongoClient**(), **archiveDatabaseName**);
    }

    public MongoClient *archiveMongoClient*() {
        ConnectionString connString= new ConnectionString(**archiveHostName**);
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyConnectionString(connString)
                .retryWrites(true)
                .build();
        return MongoClients.create(settings);
    }

    @Bean(name = "mongoArchiveTemplate")
    @Primary
    public MongoTemplate *archiveMongoTemplate*()  {
        return new MongoTemplate(**archiveMongoDbFactory**());
    }

    @Value("${spring.data.mongodb.service.host}")
    String serviceHostName;
    @Value("${spring.data.mongodb.service.database}")
    String serviceDatabaseName;

    @Bean
    public SimpleMongoClientDatabaseFactory *serviceMongoDbFactory*(){
        return new SimpleMongoClientDatabaseFactory(**serviceMongoClient**(), **serviceDatabaseName**);
    }

    public MongoClient *serviceMongoClient*() {
        ConnectionString connString= new ConnectionString(**serviceHostName**);
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyConnectionString(connString)
                .retryWrites(true)
                .build();
        return MongoClients.create(settings);
    }

    @Bean(name = "mongoServiceTemplate")
    public MongoTemplate *mongoServiceTemplate*()  {
        return new MongoTemplate(**serviceMongoDbFactory**());
    }

//    ---------------------- Below Repository base Packages, Template Class
    @Configuration
    @EnableMongoRepositories(basePackages = "**com.pf.server.archive.repository**",
        mongoTemplateRef = "mongoArchiveTemplate")
    public class ArchiveConfig {

    }

    @Configuration
    @EnableMongoRepositories(basePackages = "**com.pf.server.service.repository**",
        mongoTemplateRef = "mongoServiceTemplate")
    public class ServiceConfig {
    }

}

StockServiceTest.java

package com.pf.server.process;

import com.google.gson.Gson;
import com.pf.server.archive.domain.KrxListedStocks;
import com.pf.server.archive.repository.KrxListedStocksRepository;
import com.pf.server.service.repository.StockRepository;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import springfox.documentation.spring.web.json.Json;

import static org.junit.Assert.assertNotNull;

@SpringBootTest
@RunWith(SpringRunner.class)
class StockServiceTest {

    @Autowired
    Gson gson;

    @Autowired
    MongoTemplate mongoServiceTemplate;

    @Autowired
    MongoTemplate mongoArchiveTemplate;

    @Autowired
    StockRepository stockRepository;

    @Autowired
    KrxListedStocksRepository krxListedStocksRepository;

    @Test
    void makeStock() {
//                    where 조건 추가 방법 
        Query query = new Query(Criteria.where("creationDate").is("20201230"));
        Query query2 = new Query(Criteria.where("_id").is(new ObjectId("5ff378d01771886191254abb")));

//        Json String return
        String s  = mongoArchiveTemplate.findOne(query, String.class, "krxListedStocks");

//        Java POJO return
        KrxListedStocks convertedItem = gson.fromJson(s, KrxListedStocks.class);

//        Bson Document return
        Document document = mongoArchiveTemplate.findOne(query, Document.class, "krxListedStocks");


        List<KrxListedStocks.Stocks> stocks =  convertedItem.getContents().get(0).contents;

//        inner class using 
        List<Document> contents = document.getList("contents", Document.class).get(0).getList("contents", Document.class);

        List<KrxListedStocks> krxListedStock= krxListedStocksRepository.findBy_id(new ObjectId("5ff378d01771886191254abb"));

        List<KrxListedStocks> krxListedStocks= krxListedStocksRepository.findByCreationDate("20201230");

        assertNotNull(krxListedStocks);
    }
}

application.yml

spring:
    autoconfigure.exclude: org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

    #spring.data.mongodb.host=mongodb://
    #spring.data.mongodb.port=27017
    #spring.data.mongodb.username=username
    #spring.data.mongodb.password=password

    data.mongodb.authentication-database: admin
    data.mongodb.service.host: mongodb+srv://
    data.mongodb.service.database: service

    data.mongodb.archive.host: mongodb+srv://
    data.mongodb.archive.database: archive

build.gradle

plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

group = 'com.pfolio'
version = '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}

apply plugin: 'java'
apply plugin: 'io.spring.dependency-management'

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' 
}

test {
    useJUnitPlatform()
}
728x90
반응형