DB/MongoDB

[mongodb] spring boot 연동

벨포트조던 2019. 2. 22.
반응형

[환경]

몽고db 문서  - https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories

springboot 2

gradle 

mongodb replica set 


spring으로 단순히 몽고db 연결하는 건 자료가 많다. 

레플리카 셋으로 구성된 mongodb는 자료를 많이 찾지 못했다.


우선 

https://falkenfighter.wordpress.com/2015/10/13/multiple-databases-with-spring-boot-mongodb-repositories/


이 사이트 기반으로 했다. 

@Configuration
public class MongoConfiguration {
    /**
     * For a clustered Mongo environment we would want to load multiple
     * hosts. This will work if we use a single host or clustered.
     *
     * If the mongo.hosts key could not be found defaults to localhost
     *
     * One of the following would exist in our Spring properties file
     * 1) mongo.hosts = localhost
     * 2) mongo.hosts = 10.1.1.1,10.1.1.2,10.1.1.3
     */
    @Value("#{'${mongo.hosts:localhost}'.split(',')}")
    private List<String> hosts;
 
    /**
     * The port our Mongo hosts are running on.
     * Defaults to 27017
     */
    @Value("${mongo.port:27017}")
    private int port;
 
    /**
     * Creates a base Mongo instance that can be configured for each
     * implementation.
     *
     * NOTE: If you are trying to connect to multiple MongoDB's then
     * you would want to create 2 instances of this method as beans
     * loading the correct mongo hosts. For my implementation I just
     * wanted different global configurations pointed at the same
     * database.
     *
     * @return A generic Mongo instance pointed at the hosts.
     * @throws Exception
     */
    private Mongo createMongo() throws Exception {
        final List<ServerAddress> serverList = new ArrayList<>();
        for (final String host : hosts) {
            serverList.add(new ServerAddress(host, port));
        }
         
        // MongoClientOptions would be created here and passed into
        // the MongoClient as it's second param.
        return new MongoClient(serverList);
    }
     
    @Primary
    @Bean
    public Mongo readFromSecondaryNodeMongo() {
        final Mongo mongo = createMongo();
        // Do custom global configuration
        mongo.setReadPreference(ReadPreference.secondaryPreferred());
        return mongo;
    }
     
    @Bean
    public Mongo readFromPrimaryNodeMongo() {
        final Mongo mongo = createMongo();
        mongo.setReadPreference(ReadPreference.primaryPreferred());
        return mongo;
    }
 
    /**
     * This is the default DB Factory and will have the
     * readFromSecondaryNodeMongo() bean injected due to the @Primary
     * annotation
     *
     * @param mongo auto injected using the @Primary bean
     * @return a new MongoDbFactory
     */
    @Bean
    public MongoDbFactory mongoDbFactory(Mongo mongo) {
        return new SimpleMongoDbFactory(mongo, "DatabaseName");
    }
}



기본 spring 과 방식이 달라서 헤맨점도 있고, @어노테이션 및 빈을 자세히 알고있지 않았던거 같다.

application.properties 에
spring.data.mongo.permission.hosts = 172.30.40.40,172.30.41.40,172.30.40.41

이런식으로 ip 선언하여 사용함.


내가 개발해야되는게 기존 spring 을 springboot 로 옴겨야 하는 과정이다.

찾아보면 mongoclient 를 빈으로 만드는게 아니고, mongofactory 를 빈으로 생성하여 사용하는 자료가 많다.

factory를 생성하려면 database를 지정해주어야 한다. 그렇게 되면 database마다 bean이 생성되어서 지금상황과 맞지 않앗다.


몽고db에 접근해야할 database 가 많다. 그래서 factory로 bean을 선언하기가 좀 그렇다.

 SimpleMongoDbFactory 로 작업을 하려했지만, 위와같은 이유로 MongoClient 로 사용했다.


//    MongoTemplate templateOne = new MongoTemplate(new SimpleMongoDbFactory(new MongoClientURI("YOUR_MONGO_URL")));

//        templateOne.setReadPreference(ReadPreference.secondaryPreferred());


다른 자료에는 이런식으로 mongotemplate 을 사용한다. 이렇게 사용하는 자료가 대다수엿다.

또한 MongoRepository  이걸 사용하여 자동으로 document 를 주입하는게 많았다. 커스텀하게 사용하기보다는 dto,vo를 생성하여 사용하는 느낌.



내 방식때문에 


MongoClient 를 사용하고 @Autowired로 주입받아서 사용했다.


db2 = bb.getDatabase("permission");

MongoCollection<Document> PermissionCollection = db2.getCollection("userService")

.withReadPreference(ReadPreference.secondaryPreferred());


요런식으로 ..


최대한 bean으로 셋팅할수있는건 다 해보려고 했지만 지금으로선 여기까지가 최선






그리고

http://www.javaoptimum.com/multiple-mongodb-connections-spring-boot/

멀티 db를 구현시켜주는 거



반응형

댓글