forked from vert-x3/vertx-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExecBlockingExample.java
52 lines (36 loc) · 1.27 KB
/
ExecBlockingExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package io.vertx.example.core.execblocking;
import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
/*
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class ExecBlockingExample extends AbstractVerticle {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(ExecBlockingExample.class);
}
@Override
public void start() throws Exception {
vertx.createHttpServer().requestHandler(request -> {
// Let's say we have to call a blocking API (e.g. JDBC) to execute a query for each
// request. We can't do this directly or it will block the event loop
// But you can do this using executeBlocking:
vertx.<String>executeBlocking(future -> {
// Do the blocking operation in here
// Imagine this was a call to a blocking API to get the result
try {
Thread.sleep(500);
} catch (Exception ignore) {
}
String result = "armadillos!";
future.complete(result);
}, res -> {
if (res.succeeded()) {
request.response().putHeader("content-type", "text/plain").end(res.result());
} else {
res.cause().printStackTrace();
}
});
}).listen(8080);
}
}