はじめに
Jersey と Grizzly を使って簡単な JAX-RS アプリケーションを作っていきます。
Glassfish などの JavaEE アプリケーションサーバに組み込まれている Jersey と Grizzly ですが、単体ライブラリとしても簡単に使うことができます。
これらのライブラリを使って、main メソッドから起動する「重くない」アプリケーションを作りながら JAX-RS に触れていきます。
JAX-RS とは
JAX-RS 1.1(Java API for RESTful Web Services) として JSR-311 で策定された仕様で、JavaEE6 に取り込まれました。
JAX-RS 2.0 は JSR-339 で策定された仕様で、こちらは JavaEE7 に取り込まれています。2.0 仕様 では Client API やフィルター/インタセプターの仕様が追加されています。
JAX-RS を使うことで、POJO(Plain Old Java Object)をベースに HTTP関連のアノテーションを使うことで RESTful Web Services を簡単に実現することができます。そして仕様自体もとてもシンプルで扱いやすいものとなっています。
Jersey とは
Jersey は JAX-RX の参照実装です。
Jersey 2.0 からは HK2(JSR-330 の DI実装) が組み込まれていたり、Jersey MVC(JavaEE8で導入されるMVC 1.0の元になる) があったり、これだけでも簡単なアプリケーションが作れます。
Grizzly とは
Grizzly は Glassfish の HTTP処理エンジン(以前は Coyote が使われていた)として使われています。
NIOを使用してC10K問題に対応したハイパフォーマンスで汎用的なネットワークサーバエンジンです。
プロジェクトの作成
ではプロジェクトを作成しましょう。
プロジェクトの管理には Gradle を使います。init タスクでプロジェクトの雛形を作成します。
$ mkdir example-jersey-grizzly $ cd example-jersey-grizzly $ gradle init --type java-library
init タスクにて作成された build.gradle に今回必要な依存ライブラリの指定を加えます。
以下のように変更します。
apply plugin: 'java' apply plugin: 'application' mainClassName = "example.Main" compileJava { sourceCompatibility = targetCompatibility = '1.8' } repositories { jcenter() } dependencies { // jersey-grizzly compile 'org.glassfish.jersey.containers:jersey-container-grizzly2-http:2.22.2' compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.22.2' // logger compile 'org.slf4j:slf4j-api:1.7.+' compile 'ch.qos.logback:logback-classic:1.+' testCompile 'junit:junit:4.+' } run { standardInput = System.in }
jersey-container-grizzly2-http
の依存を追加することで grizzly 上で jersey を動かすのに必要な jar が手に入ります。
合わせて Json を扱っていきたいので jersey-media-json-jackson
を指定しておきます。
grizzly の http サーバは Main から起動させるので、gradle の application
プラグインも指定して、mainClassName
の指定も入れておきました。
Main クラスの作成
Grizzly を起動する Main クラスを作成します。
jersey-container-grizzly2-http
で提供される GrizzlyHttpServerFactory
を使えば、Jersey と連携する Grizzly サーバを簡単に起動することができます。
package example; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.UriBuilder; import java.awt.*; import java.io.IOException; import java.net.URI; public class Main { private static Logger log = LoggerFactory.getLogger(Main.class); static final URI BASE_URI = UriBuilder.fromUri("http://localhost/").port(8090).build(); public static void main(String[] args) throws IOException { final HttpServer server = GrizzlyHttpServerFactory.createHttpServer( BASE_URI, ResourceConfig.forApplicationClass(RsResourceConfig.class)); Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow)); openBrowser(); log.info("Start grizzly. Press any key to exit."); System.in.read(); System.exit(0); } private static void openBrowser() { try { if (Desktop.isDesktopSupported()) Desktop.getDesktop().browse(Main.BASE_URI); } catch (IOException ignore) { log.error("fail to launch browser.", ignore); } } public static class RsResourceConfig extends ResourceConfig { public RsResourceConfig() { packages("example.web.resource"); } } }
やっていることは GrizzlyHttpServerFactory#createHttpServer()
で HttpServer を作成して起動しているだけです。
createHttpServer()
の引数には、アプリケーションのルートパスと JAX-RS 用の設定クラス ResourceConfig
を指定します。このクラスはインナークラス RsResourceConfig
として定義しており、JAX-RS のリソースクラスを配置するパッケージを指定しています。
では、JAX-RS のリソースクラスを作成していきましょう。
Resource クラスの作成
Resource クラスは POJO に @Path
アノテーションを付けて定義します。
package example.web.resource; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/") public class Index { @GET public Response hello() { return Response.ok("Hello jersey-grizzly!!").build(); } }
@Path
にてHTTPリクエストのパス指定しています。
@GET
にてアノテートした hello() メソッドから文字列のレスポンスを返しています。
実行
実行してみましょう。
Gradle のアプリケーションプラグインを設定しているので以下のようにするだけです。
$ ./gradlew run
ブラウザが立ち上がって以下のように表示されれば OK です。
簡単ですね。
ここまでのソースはGithubを参照してください。
次回は作成したプロジェクトを使って JAX-RS について細かく見ていきましょう。