Spring BootとArmeriaでHTTP/2のh2cを試す

Spring BootはHTTP/2のh2c (HTTP/2 over TCP)をサポートしていないが、Armeriaを組み合わせると使用できる。

追記
- Spring Boot 2.3.5からh2cの設定方法がドキュメントに記載されたので、Armeriaを使わなくても試せるようになった。
https://docs.spring.io/spring-boot/docs/2.4.x/reference/html/howto.html#howto-configure-http2-h2c
- Spring Boot 2.5からはserver.http2.enabledtrueにするだけでh2cを使用できるようになった。
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes

準備

ソースコード

Spring Initializrでプロジェクトを作成する。
https://start.spring.io/

application.propeties

http2を有効にする。

server.http2.enabled=true

build.gradle

Armeriaのdependenciesを追加する。

dependencies {
    implementation platform('com.linecorp.armeria:armeria-bom:1.0.0')
    implementation 'com.linecorp.armeria:armeria-spring-boot2-webflux-starter'
}

HelloController.java

Controllerを追加する。

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Mono<String> hello() {
        return Mono.just("Hello!");
    }
}

動作確認

ブラウザはh2cをサポートしていないため、curlコマンドで確認する。

% curl -v --http2 http://localhost:8080/hello
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /hello HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> Connection: Upgrade, HTTP2-Settings
> Upgrade: h2c
> HTTP2-Settings: AAMAAABkAARAAAAAAAIAAAAA
> 
< HTTP/1.1 101 Switching Protocols
< connection: upgrade
< upgrade: h2c
* Received 101
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=84
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 200 
< content-type: text/plain;charset=UTF-8
< content-length: 6
< 
* Connection #0 to host localhost left intact
Hello!

h2cなので、Wiresharkでも確認できる。

参考

https://docs.spring.io/spring-boot/docs/2.2.1.RELEASE/reference/html/howto.html#howto-configure-http2
https://armeria.dev/docs/advanced-spring-webflux-integration
https://github.com/spring-projects/spring-boot/issues/21997