kok202
Reactive connection with DB

2019. 4. 18. 14:28[개발] 기록

Repository 가 Non reactive 일 경우

1. find

@Autowired
private MyRepository myRepository;

public void test(){
        MyEntity myEntity = myRepository.findById("test-key");
        System.out.println(myEntity.getKey());
}

 

2. save and find

@Autowired
private MyRepository myRepository;

public void test(){
        myRepository.save(new MyEntity("test-key", "message"));
        MyEntity myEntity = myRepository.findById("test-key");
        System.out.println(myEntity.getKey());
}

 

 

 

 


Repository 가 Reactive 일 경우

1. Return type 은 Mono<> 또는 Flux<> 이다. 

-> Mono : 0~1

-> Flux : 0~n

-> Mono, Flux는 Publisher다.

2. Mono, Flux 객체를 subscribe 하기 전에는 데이터 flow 가 생기지 않는다. subscrbie를 해줘야한다.

3. block 메소드를 사용하면 동기 처리 처럼 호출할 수 있다. (Reactive 를 쓰는 의미가 퇴색되긴한다.)

 

1. find

방법 1. Mono 객체에 객체가 들어올 때까지 block 해서 받는다.

@Autowired
private MyRepository myRepository;

public void test(){
        Mono<MyEntity> monoMyEntity = myRepository.findById("test-key");
        MyEntity myEntity = monoMyEntity.block();
        System.out.println(myEntity.getKey());
}

방법 2. subscribe 해서 flow가 흐르도록 해준다.

subscribe 안에는 데이터가 흘러들어왔을때 처리할 수 있는 로직을 정의해 줄 수 있다. (lamda)

@Autowired
private MyRepository myRepository;

public void test(){
        Mono<MyEntity> monoMyEntity = myRepository.findById("test-key");
        monoMyEntity.subscribe(myEntity -> {
            System.out.println(myEntity.getKey());
        });
}

 

2. save and find

방법 1. save 가 될 때까지 block 했다가 find 를 호출한다.

@Autowired
private MyRepository myRepository;

public void test(){
        myRepository.save(new MyEntity("test-key", "message")).block();
        Mono<MyEntity> monoMyEntity = myRepository.findById("test-key");
        monoMyEntity.subscribe(myEntity -> {
            System.out.println(myEntity.getKey());
        });
}

방법 2. subscribe 시키고 완료되면 find 한다. -> 확인 필요.

//@Autowired
//private MyRepository myRepository;

//public void test(){
//        myRepository.save(new MyEntity("test-key", "message")).subscribe(temp -> {
//                Mono<MyEntity> monoMyEntity = myRepository.findById("test-key");
//                monoMyEntity.subscribe(myEntity -> {
//                        System.out.println(myEntity.getKey());
//                });
//        });
//}

 

* 테스트 코드가 block 이 아니라 subscribe 일경우 subscribe 하는 객체에 데이터가 도착하기전에 Test가 끝나버려 Reactive 결과를 볼 수 없으니 유의한다.