Module 09 · Executable guide

Vert.x Core

Verticle, Context, Future, Promise, worker model, HTTP và Event Bus.


1. Mental model

Vertx
 ├─ Event-loop contexts
 ├─ Worker contexts
 ├─ Verticles
 ├─ HTTP/TCP
 └─ Event Bus

2. VerticleBase

public final class HttpVerticle extends VerticleBase {
    @Override
    public Future<?> start() {
        return vertx.createHttpServer()
            .requestHandler(req -> req.response().end("hello"))
            .listen(8080);
    }
}

Verticle là deployment unit actor-like, không phải thread.

3. Context

Handler của một context thường chạy trên cùng event-loop thread. Điều này giảm nhu cầu locking cho state chỉ thuộc context đó, nhưng shared state vẫn cần discipline.

4. Future composition

findUser(id)
    .compose(user -> findOrders(user.id()))
    .map(orders -> new Profile(id, orders))
    .recover(err -> Future.succeededFuture(Profile.empty(id)));

5. Promise

Future là read-side; Promise là write-side để bridge callback/custom async source.

6. Blocking integration

vertx.executeBlocking(() -> legacyJdbcCall())
    .onSuccess(this::use)
    .onFailure(this::handle);

Worker pool vẫn là bounded resource; không dùng executeBlocking để che toàn bộ architecture blocking.

7. HTTP

return vertx.createHttpServer()
    .requestHandler(req -> {
        if (req.path().equals("/health")) req.response().end("OK");
        else req.response().setStatusCode(404).end();
    })
    .listen(8080);

8. Event Bus

vertx.eventBus()
    .request("inventory.check", order)
    .compose(reply -> save((Inventory) reply.body()));

Event Bus hỗ trợ point-to-point, publish/subscribe và request/reply; cần contract, timeout, codec và failure handling rõ ràng.

9. Failure handling

  • Future failure propagation.
  • Event Bus timeout/delivery failure.
  • Domain vs technical error.
  • Không swallow exception.

10. Lab

HttpVerticle → request("user.find") → UserVerticle
                                 ↓
                           request("order.find")
                                 ↓
                           OrderVerticle

Không callback hell; timeout rõ; map failure thành HTTP 404/503.