JAX-RS2.1
非同期クライアント: rx()によるCompletationState取得
// Aの問い合わせ(非同期)
WebTarget targetA = Client.newClient().target(...);
CompletionStage<User> a = target1.request().resolveTemplate(“id”, 1)
.rx().get(User.class);
// Bの問い合わせ (非同期)
CompletionState<Product> b = targetB.request().resolveTemplate(“id”, 1)
.rx().get(Product.class);
// AとBの結果を組み合わせて、Cに問い合わせ (非同期)
CompletionState<String> c = a.thenCombine(b, (user, product) ->
targetC.request()
.resolveTemplate(“user”,user)
.resolveTemplate(“prod”,product).rx().get(...)));
// 最終的な結果の取得
c.join();
a
b
c 最終的な結果
16.
JAX-RS2.1
非同期クライアント: rx()によるCompletationState取得
// Aの問い合わせ(非同期)
WebTarget targetA = Client.newClient().target(...);
CompletionStage<User> a = target1.request().resolveTemplate(“id”, 1)
.rx().get(User.class);
// Bの問い合わせ (非同期)
CompletionState<Product> b = targetB.request().resolveTemplate(“id”, 1)
.rx().get(Product.class);
// AとBの結果を組み合わせて、Cに問い合わせ (非同期)
CompletionState<String> c = a.thenCombine(b, (user, product) ->
targetC.request()
.resolveTemplate(“user”,user)
.resolveTemplate(“prod”,product).rx().get(...)));
// 最終的な結果の取得
c.join();
a
b
c 最終的な結果
17.
JAX-RS2.1
非同期クライアント: アノテーションによる依存性制御
class DeclarativeRxHandler{
@FinalResult
public String getC(
@PartialResult(“A”) String a, @PartialResult(“B”) String b) {
return a;
}
@PartialResult(“A”)
public CompletableFuture<String> getA() {...}
@PartialResult(“B”)
public CompletableFuture<String> getB() {...}
}
A
B
C 最終的な結果
18.
JAX-RS2.1
ノンブロッキング I/O -背景
• 不安定/遅いネットワークからファイルアップロード
• CPUは別スレッドに割当てられても、メモリは1MB消費し続ける
@Path(“/upload”)
public class FileUploadResource {
@POST @Consumes(MediaType.MULTIPART_FORM_DATA)
public void upload(@FormDataParam(“file”) InputStream input, ...) {
byte[] buf = new byte[1024];
int readed;
try {
while ((readed = input.read(buf)) != -1) {
// write file ...
} catch (IOException e) {...}
}
データが来るまでブロック
(64bitJVM)
19.
@POST @Consumes(MediaType.APPLICATION_OCTET_STREAM)
public voidupload(@QueryParam(“path”) String path,
@Context request, @Suspend AsyncResponse response) {
FileOutputStream out = new FileOutputStream(tmpdir);
byte[] buf = new byte[1024];
request.entity(input -> {
try {
if (input.isFinished()) {
// データ読み込み完了
out.close();
response.resume(“Upload Completed”);
} else {
final int n = input.read(buffer);
out.write(buffer, 0, n);
}
} catch (IOException e) {...}
}
}
JAX-RS2.1
ノンブロッキング I/O - JavaOneで紹介されていたアイディア
20.
@POST @Consumes(MediaType.APPLICATION_OCTET_STREAM)
public voidupload(@QueryParam(“path”) String path,
@Context request, @Suspend AsyncResponse response) {
FileOutputStream out = new FileOutputStream(tmpdir);
byte[] buf = new byte[1024];
request.entity(input -> {
try {
if (input.isFinished()) {
// データ読み込み完了
out.close();
response.resume(“Upload Completed”);
} else {
final int n = input.read(buffer);
out.write(buffer, 0, n);
}
} catch (IOException e) {...}
}
}
ブロックしない
読込可能データの発生毎に
繰り返しコールバックされる?
JAX-RS2.1
ノンブロッキング I/O - JavaOneで紹介されていたアイディア