はじめてのSpring WebFlux (その1 - Spring WebFluxを試す)ではSpring Boot 2.0を使用してSpring WebFluxアプリケーションを作成しましたが、今回は番外編としてSpring WebFluxをマニュアルでBootstrapしてみます。 方法はドキュメントに書かれています。
アノテーションベースの@Controllerモデルでも関数型ベースのRouter Functionsモデルでもorg.springframework.http.server.reactive.HttpHandler
に変換するところがポイントです。
HttpHandler
に変換した後は各種ランタイムのアダプタに渡して、ランタイムを実行する流れになります。
本記事ではRouter FunctionsモデルでReactor Nettyランタイムを使う方法のみ紹介します。
目次
プロジェクト作成
Spring Bootを使わないと言いましたが、プロジェクト自体はSpring Initializrから作成した方が楽です。Spring Initializrの雛形クラスから不要なものを削除していきます。
次のコマンドでプロジェクトを作成します。
curl https://start.spring.io/starter.tgz \
-d bootVersion=2.0.0.BUILD-SNAPSHOT \
-d artifactId=manual-webflux \
-d baseDir=manual-webflux \
-d dependencies=webflux \
-d applicationName=ManualWebFluxApplication | tar -xzvf -
まずは前記事と同じくSpring BootでRouter FunctionsのHello Worldから始めます。
ManualWebFluxApplication.java
に次のコードを記述してください。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
@SpringBootApplication
public class ManualWebFluxApplication {
public static void main(String[] args) {
SpringApplication.run(ManualWebFluxApplication.class, args);
}
@Bean
RouterFunction<ServerResponse> routes() {
return route(GET("/"), req -> ok().syncBody("Hello World!"));
}
}
このコードの意味がわからなければはじめてのSpring WebFlux (その1 - Spring WebFluxを試す)を読み直してください。
次にRouterFunction<ServerResponse>
をHttpHandler
に変換する必要がありますが、これはRouterFunctions.toHttpHandler
を使えば簡単です。
一旦、ManualWebFluxApplication
からSpring Boot関連のコードを削り、HttpHandler
を作るところまで書きます。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
public class ManualWebFluxApplication {
public static void main(String[] args) {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes());
}
static RouterFunction<ServerResponse> routes() {
return route(GET("/"), req -> ok().syncBody("Hello World!"));
}
}
ここまではSpring WebFluxの世界です。
次はReactor Nettyの世界に移ります。HttpHandler
からReactor Nettyのハンドラに変換して、Reactor NettyのWebサーバー機能を担うHttpServer
に渡します。
HttpHandler
からReactor Nettyのハンドラへの変換はorg.springframework.http.server.reactive.ReactorHttpHandlerAdapter
を嚙ますのみです。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
public class ManualWebFluxApplication {
public static void main(String[] args) {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes());
HttpServer httpServer = HttpServer.create("0.0.0.0", 8080);
Mono<? extends NettyContext> handler = httpServer
.newHandler(new ReactorHttpHandlerAdapter(httpHandler));
}
static RouterFunction<ServerResponse> routes() {
return route(GET("/"), req -> ok().syncBody("Hello World!"));
}
}
最後にWebサーバーの待機と終了待ち合わせのためにNettyの世界に入ります。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import io.netty.channel.Channel;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
public class ManualWebFluxApplication {
public static void main(String[] args) throws Exception {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes());
HttpServer httpServer = HttpServer.create("0.0.0.0", 8080);
Mono<? extends NettyContext> handler = httpServer
.newHandler(new ReactorHttpHandlerAdapter(httpHandler));
Channel channel = handler.block().channel();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
channel.eventLoop().shutdownGracefully().sync();
}
catch (InterruptedException ignore) {
}
}));
channel.closeFuture().sync();
}
static RouterFunction<ServerResponse> routes() {
return route(GET("/"), req -> ok().syncBody("Hello World!"));
}
}
後はsrc/main/resource/application.properties
を削除して、お好みでlogback.xml
を作ってください。
サンプルを貼っておきます。
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %5p --- [%15.15t] %-40.40logger{39} : %m%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
<logger name="reactor.ipc.netty" level="DEBUG"/>
</configuration>
これでManualWebFluxApplication
を再起動して、http://localhost:8080にアクセスしてください。
次のようなログが出力されるでしょう。
2017-05-10 04:07:37.873 DEBUG --- [ main] r.i.n.r.DefaultLoopEpollDetector : Default epoll support : false
2017-05-10 04:07:37.962 DEBUG --- [ main] r.i.n.channel.CloseableContextHandler : Connecting new channel: AbstractBootstrap$PendingRegistrationPromise@61d6015a(incomplete)
2017-05-10 04:07:37.978 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3] REGISTERED
2017-05-10 04:07:37.980 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3] BIND: /0.0.0.0:8080
2017-05-10 04:07:38.036 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] ACTIVE
2017-05-10 04:07:44.686 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] READ: [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362]
2017-05-10 04:07:44.687 DEBUG --- [ctor-http-nio-1] r.ipc.netty.http.server.HttpServer : [id: 0xa7ca25f3, L:/0:0:0:0:0:0:0:0:8080] READ COMPLETE
2017-05-10 04:07:44.727 DEBUG --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations : New http connection, requesting read
2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.channel.ContextHandler : After pipeline DefaultChannelPipeline{(reactor.left.loggingHandler = io.netty.handler.logging.LoggingHandler), (ServerContextHandler#0 = reactor.ipc.netty.channel.ServerContextHandler), (reactor.left.httpDecoder = io.netty.handler.codec.http.HttpRequestDecoder), (reactor.left.httpEncoder = io.netty.handler.codec.http.HttpResponseEncoder), (reactor.left.httpServerHandler = reactor.ipc.netty.http.server.HttpServerHandler), (reactor.right.reactiveBridge = reactor.ipc.netty.channel.ChannelOperationsHandler)}
2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] REGISTERED
2017-05-10 04:07:44.729 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] ACTIVE
2017-05-10 04:07:44.740 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ: 78B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a |GET / HTTP/1.1..|
|00000010| 48 6f 73 74 3a 20 6c 6f 63 61 6c 68 6f 73 74 3a |Host: localhost:|
|00000020| 38 30 38 30 0d 0a 55 73 65 72 2d 41 67 65 6e 74 |8080..User-Agent|
|00000030| 3a 20 63 75 72 6c 2f 37 2e 34 33 2e 30 0d 0a 41 |: curl/7.43.0..A|
|00000040| 63 63 65 70 74 3a 20 2a 2f 2a 0d 0a 0d 0a |ccept: */*.... |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.750 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ COMPLETE
2017-05-10 04:07:44.751 DEBUG --- [ctor-http-nio-2] r.ipc.netty.channel.ChannelOperations : [HttpServer] [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] handler is being applied: org.springframework.http.server.reactive.ReactorHttpHandlerAdapter@14c85872
2017-05-10 04:07:44.802 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object DefaultHttpResponse(decodeResult: success, version: HTTP/1.1)
HTTP/1.1 200 OK
transfer-encoding: chunked
Content-Type: text/plain;charset=UTF-8
2017-05-10 04:07:44.810 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 87B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d |HTTP/1.1 200 OK.|
|00000010| 0a 74 72 61 6e 73 66 65 72 2d 65 6e 63 6f 64 69 |.transfer-encodi|
|00000020| 6e 67 3a 20 63 68 75 6e 6b 65 64 0d 0a 43 6f 6e |ng: chunked..Con|
|00000030| 74 65 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f |tent-Type: text/|
|00000040| 70 6c 61 69 6e 3b 63 68 61 72 73 65 74 3d 55 54 |plain;charset=UT|
|00000050| 46 2d 38 0d 0a 0d 0a |F-8.... |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.811 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH
2017-05-10 04:07:44.814 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object { "operator" : "Map" }
2017-05-10 04:07:44.817 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 3B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 0d 0a |c.. |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.818 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 12B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 48 65 6c 6c 6f 20 57 6f 72 6c 64 21 |Hello World! |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.819 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 2B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 0d 0a |.. |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.819 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH
2017-05-10 04:07:44.821 DEBUG --- [ctor-http-nio-2] r.i.n.http.server.HttpServerOperations : Last HTTP response frame
2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Writing object EmptyLastHttpContent
2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] WRITE: 5B
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 30 0d 0a 0d 0a |0.... |
+--------+-------------------------------------------------+----------------+
2017-05-10 04:07:44.822 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] FLUSH
2017-05-10 04:07:44.824 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] USER_EVENT: [Handler Terminated]
2017-05-10 04:07:44.826 DEBUG --- [ctor-http-nio-2] r.i.n.channel.ChannelOperationsHandler : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] Disposing context reactor.ipc.netty.channel.ServerContextHandler@5286385e
2017-05-10 04:07:44.826 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 - R:/0:0:0:0:0:0:0:1:60362] READ COMPLETE
2017-05-10 04:07:44.829 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 ! R:/0:0:0:0:0:0:0:1:60362] INACTIVE
2017-05-10 04:07:44.829 DEBUG --- [ctor-http-nio-2] r.ipc.netty.http.server.HttpServer : [id: 0x8a9527a1, L:/0:0:0:0:0:0:0:1:8080 ! R:/0:0:0:0:0:0:0:1:60362] UNREGISTERED
後はpom.xml
を整理しましょう。基本的には次の<dependency>
だけですみます。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>manual-webflux</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor.ipc</groupId>
<artifactId>reactor-netty</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
これでManualWebFluxApplication
を再起動し、同じく動作することを確認してください。
これで最小限のSpring WebFluxアプリケーションが立ち上がりました。かなりメモリフットプリントを小さく抑えられると思います。
勘の良い人は気づいたと思いますが、ここまでSpringのDIコンテナであるApplicationContext
を使っていません(!)。
Spring WebFlux + RouterFunctionsの場合はDIコンテナなしでも起動します。
前記事同様にDIコンテナを使ってRouterFunctions
をBean定義する方法を次に見ていきましょう。
AnnotationベースのBean定義
はじめてのSpring WebFlux (その1 - Spring WebFluxを試す)で作成した次のEchoHandler
をコンポーネントスキャンする例を示します。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class HelloHandler {
public RouterFunction<ServerResponse> routes() {
return route(GET("/"), this::hello);
}
Mono<ServerResponse> hello(ServerRequest req) {
return ok().body(Flux.just("Hello", "World!"), String.class);
}
}
今回はManualWebFluxApplication
クラスをJavaConfigクラスとして使います。なので、ManualWebFluxApplication
に@Configuration
アノテーションをつけます [1]。また、コンポーネントスキャンを有効にするためにManualWebFluxApplication
に@ComponentScan
アノテーションをつけます [2]。これで、com.example
パッケージ配下がコンポーネントスキャン対象になります。
DIコンテナであるApplicationContext
を作成します。ここでは汎用的なGenericApplicationContext
を使用します。ルートとなるJavaConfigはAnnotationConfigApplicationContext
のコンストラクタに渡せば良いです [3]。
ApplicationContext
を使う場合は、HttpHandler
をWebHttpHandlerBuilder
で作成できます [4]。この場合、Router Functionsを使うにはDIコンテナにはBean名がwebHandler
であるorg.springframework.web.server.WebHandler
型のBeanが登録されいる必要があります。RouterFunction<ServerResponse>
からWebHandler
に変換する際にもRouterFunctions.toHttpHandler
が使えます。これを@Bean
のついたメソッドで定義します [5]。
(実はRouterFunctions.toHttpHandler
はHttpHandler
兼WebHandler
であるorg.springframework.web.server.adapter.HttpWebHandlerAdapter
を返します)
package com.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import io.netty.channel.Channel;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
@Configuration // [1]
@ComponentScan // [2]
public class ManualWebFluxApplication {
public static void main(String[] args) throws Exception {
// [3]
GenericApplicationContext context = new AnnotationConfigApplicationContext(
ManualWebFluxApplication.class);
context.registerShutdownHook();
// [4]
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context)
.build();
HttpServer httpServer = HttpServer.create("0.0.0.0", 8080);
Mono<? extends NettyContext> handler = httpServer
.newHandler(new ReactorHttpHandlerAdapter(httpHandler));
Channel channel = handler.block().channel();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
channel.eventLoop().shutdownGracefully().sync();
}
catch (InterruptedException ignore) {
ignore.printStackTrace();
}
}));
channel.closeFuture().sync();
}
// [5]
@Bean
WebHandler webHandler(HelloHandler helloHandler) {
return RouterFunctions.toHttpHandler(helloHandler.routes());
}
}
これでManualWebFluxApplication
を再起動して、http://localhost:8080にアクセスすればHelloWorld!が表示されるでしょう。
以降、HelloHandler
の作り方は普通のSpringアプリケーションと同じです。
FunctionalなBean定義
今度はSpring 5で導入されたFunctional Bean Registrationを使い、アノテーションを一切使わず、Functionalな方法でBean定義します。
まずはEchoController
から@Controller
を外します。
package com.example;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class HelloHandler {
public RouterFunction<ServerResponse> routes() {
return route(GET("/"), this::hello);
}
Mono<ServerResponse> hello(ServerRequest req) {
return ok().body(Flux.just("Hello", "World!"), String.class);
}
}
次にいよいよFunctional Bean Registrationを行います。@Configuration
、@ComponentScan
、@Bean
メソッドはもう削除してください。
Bean定義はGenericApplicationContext#registerBean(Class<T>, Supplier<T>, org.springframework.beans.factory.config.BeanDefinitionCustomizer...)
メソッドで行えます。
HelloHandler
とWebHandler
をregister(Class<T>, Supplier<T>)
で定義して、GenericApplicationContext
をrefresh
すればDIコンテナ作成完了です。
package com.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.server.WebHandler;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
import io.netty.channel.Channel;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
public class ManualWebFluxApplication {
public static void main(String[] args) throws Exception {
GenericApplicationContext context = new AnnotationConfigApplicationContext();
context.registerBean(HelloHandler.class, HelloHandler::new); // context.registerBean(HelloHandler.class)でもOK
context.registerBean(WebHandler.class, () -> RouterFunctions
.toHttpHandler(context.getBean(HelloHandler.class).routes()));
context.refresh();
context.registerShutdownHook();
HttpHandler httpHandler = WebHttpHandlerBuilder.applicationContext(context)
.build();
HttpServer httpServer = HttpServer.create("0.0.0.0", 8080);
Mono<? extends NettyContext> handler = httpServer
.newHandler(new ReactorHttpHandlerAdapter(httpHandler));
Channel channel = handler.block().channel();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
channel.eventLoop().shutdownGracefully().sync();
}
catch (InterruptedException ignore) {
ignore.printStackTrace();
}
}));
channel.closeFuture().sync();
}
}
これでManualWebFluxApplication
を再起動して、http://localhost:8080にアクセスすればHelloWorld!が表示されます。
Spring BootもアノテーションなしでSpringのWebアプリケーションが作れるようになりました🙌
本記事ではSpring WebFluxの番外編としてSpring Bootを使わない方法を説明しました。多分数十MB前後のヒープでも動作すると思います。
とはいえ普段はSpring Boot 2.0でWebFluxアプリケーションを書くことになるでしょうが、 遊びでも、中身を知る上でもマニュアル起動の方法を知っていおくことはためになるでしょう。
次回は本線に戻って、WebClient
とテストサポートについて説明します。