Spring BootでRxJava2を使う
Spring Boot 2はRxJava2をサポートしているので、Spring MVCとSpring WebFluxどちらでも、Controllerの戻り値にFlowableなどを指定できる。
ソースコード
dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'io.reactivex.rxjava2:rxjava' }
@RestController public class HelloController { @GetMapping("/hello1") public Single<String> hello1() { return Single.just("Hello!"); } @GetMapping("/hello2") public Flowable<String> hello2() { return Flowable.fromIterable(List.of("Hello!", "Hello!")); } @GetMapping(value = "/hello3", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flowable<String> hello3() { return Flowable.fromIterable(List.of("Hello!", "Hello!")); } }
参考
- https://docs.spring.io/spring-framework/docs/5.2.1.RELEASE/spring-framework-reference/web.html#mvc-ann-return-types
- https://docs.spring.io/spring-framework/docs/5.2.1.RELEASE/spring-framework-reference/web.html#mvc-ann-async-reactive-types
- https://docs.spring.io/spring-framework/docs/5.2.1.RELEASE/spring-framework-reference/web-reactive.html#webflux-ann-return-types