Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Services réactifs avec Vert.x et intégration av...
Search
Julien Ponge
November 09, 2017
Programming
0
190
Services réactifs avec Vert.x et intégration avec Kotlin
Lyon Meetup User Group, November 2017
Julien Ponge
November 09, 2017
Tweet
Share
More Decks by Julien Ponge
See All by Julien Ponge
Quarkus Insights 2023-03-06
jponge
0
62
Reactive Streams. 4 Interfaces. Et après ?
jponge
0
35
Scalability and resilience in practice: current trends and opportunities
jponge
0
260
Eclipse Vert.x at BruJUG 2019
jponge
0
160
Du réactif au service du pneu connecté
jponge
0
300
Bringing Reactive to Enterprise Java Developers
jponge
0
280
Golo LyonJUG 2019
jponge
0
250
Vert.x Montreal JUG 2018
jponge
0
420
Bringing Reactive to Enterprise Application Developer // Reactive Summit 2018
jponge
0
230
Other Decks in Programming
See All in Programming
PHPで作るWebSocketサーバー ~リアクティブなアプリケーションを知るために~ / WebSocket Server in PHP - To know reactive applications
seike460
PRO
2
470
テストコード書いてみませんか?
onopon
2
130
創造的活動から切り拓く新たなキャリア 好きから始めてみる夜勤オペレーターからSREへの転身
yjszk
1
130
Jakarta EE meets AI
ivargrimstad
0
260
コンテナをたくさん詰め込んだシステムとランタイムの変化
makihiro
1
130
PHPUnitしか使ってこなかった 一般PHPerがPestに乗り換えた実録
mashirou1234
0
210
CQRS+ES の力を使って効果を感じる / Feel the effects of using the power of CQRS+ES
seike460
PRO
0
140
create_tableをしただけなのに〜囚われのuuid編〜
daisukeshinoku
0
260
開発者とQAの越境で自動テストが増える開発プロセスを実現する
92thunder
1
190
Fibonacci Function Gallery - Part 1
philipschwarz
PRO
0
220
Keeping it Ruby: Why Your Product Needs a Ruby SDK - RubyWorld 2024
envek
0
190
17年周年のWebアプリケーションにTanStack Queryを導入する / Implementing TanStack Query in a 17th Anniversary Web Application
saitolume
0
250
Featured
See All Featured
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
10
810
Rails Girls Zürich Keynote
gr2m
94
13k
How to Create Impact in a Changing Tech Landscape [PerfNow 2023]
tammyeverts
48
2.2k
Thoughts on Productivity
jonyablonski
67
4.4k
Done Done
chrislema
181
16k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
95
17k
The Invisible Side of Design
smashingmag
298
50k
Building Applications with DynamoDB
mza
91
6.1k
Designing on Purpose - Digital PM Summit 2013
jponch
116
7k
No one is an island. Learnings from fostering a developers community.
thoeni
19
3k
Stop Working from a Prison Cell
hatefulcrawdad
267
20k
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
44
6.9k
Transcript
Services réactifs avec Vert.x et intégration avec Kotlin Julien Ponge
— @jponge 2017/11/09 — Lyon Kotlin User Group
None
Julien Ponge Maitre de Conférences “Delegated consultant to Red Hat”
on Vert.x Eclipse Golo + extensive F/OSS background ! https://julien.ponge.org/ " @jponge # @jponge https://www.mixcloud.com/hclcast/
Outline ✓ Reactive? Vert.x? ✓ Vert.x core 101 ✓ Reactive
extensions with RxJava 2 ✓ Kotlin coroutines and Vert.x
Reactive? Vert.x?
None
Application
Software Messages Requests Metrics Availability
Reactive systems Reactive streams Reactive programming Reactive “Responding to stimuli”
Manifesto, Actor, Messages Resilience, Elasticity, Scalability, Asynchronous, non-blocking Data flow Back-pressure Non-blocking Data flow Events, Observable Spreadsheets Akka, Vert.x Akka Streams, RxJava, Reactor, Vert.x Reactor, Reactive Spring, RxJava, Vert.x
Eclipse Vert.x Open source project started in 2012 Eclipse /
Apache licensing A toolkit for building reactive applications for the JVM 7K ⋆ on & Built on top of ! https://vertx.io " @vertx_project
None
(demo) “Hello world in action”
Vert.x core — 101
Vert.x Concurrency Model
while (isRunning) { String line = bufferedReader.readLine(); switch (line.substring(0, 4))
{ case "ECHO": bufferedWriter.write(line); break // ... // other cases ( ...) // ... default: bufferedWriter.write("UNKW Unknown command"); } }
x 1000 = '
C1 “When you have a line of text, call C2”
Something else with no blocking call either C2
Events Thread Event Loop
2 event-loops per CPU core by default
Verticles ) ) ) public class SomeVerticle extends AbstractVerticle
{ @Override public void start() throws Exception { } @Override public void stop() throws Exception { } } class SomeVerticle : AbstractVerticle() { override fun start() { } override fun stop() { } } exports.vertxStart = function() { } exports.vertxStop = function() { }
) * Configuration ) ) Verticle Deploy Deploy
) Worker thread pool Blocking task + executeBlocking Result
Message passing on the event bus
) ) Http server verticle Database client verticle ?
) . ) Http server verticle Database client verticle
Event Bus / “Details for user 1234?” Send to “user.db”
) . ) Http server verticle Database client verticle
Event Bus / “Details for user 1234?” Send to “user.db” Consume from “user.db”
) . ) Http server verticle Database client verticle
Event Bus / . “Details for user 1234?” “{data}”
/ Asynchronous messaging “foo.bar”, “foo-bar”, “foo/bar”, … Point to point
(with possible response back) Publish / subscribe
/ Distributed across Vert.x nodes Hazelcast, Ignite, Infinispan, … TCP
bridge interface Go, Python, C, JavaScript, Swift, C#, … SockJS bridge Seamless frontend / backend messaging
EventBus eb = vertx.eventBus(); eb.consumer("ping-address", message -> { System.out.println("Received message:
" + message.body()); message.reply("pong!"); }); EventBus eb = vertx.eventBus(); vertx.setPeriodic(1000, v -> { eb.send("ping-address", "ping!", reply -> { if (reply.succeeded()) { System.out.println("Received reply " + reply.result().body()); } else { System.out.println("No reply"); } }); });
MessageConsumer<Buffer> consumer = eventBus.consumer(“boilervroom.audiostream"); consumer.bodyStream().handler(buffer -> { if (!response.writeQueueFull()) {
response.write(buffer); } }); Streams Backpressure, supports pausing / resuming / dropping
const eventBus = new EventBus("/eventbus") traktorIn.addListener("controlchange", 5, (event) => {
eventBus.publish("boilervroom.vu-meter", { type: "volume-level", value: event.value }) }) eventBus.publish("boilervroom.fromtraktor", { type: "filter", number: 1, value: (event.value !== 0) }) Event Bus
switch (message.headers().get("action")) { case "all-pages": fetchAllPages(message); break; case "get-page": fetchPage(message);
break; case "create-page": createPage(message); break; case "save-page": savePage(message); break; case "delete-page": deletePage(message); break; default: message.fail(ErrorCodes.BAD_ACTION.ordinal(), "Bad action: " + action); }
private void deletePage(Message<JsonObject> message) { dbClient.getConnection(car -> { if (car.succeeded())
{ SQLConnection connection = car.result(); JsonArray data = new JsonArray().add(message.body().getString("id")); connection.updateWithParams(sqlQueries.get(SqlQuery.DELETE_PAGE), data, res -> { connection.close(); if (res.succeeded()) { message.reply(new JsonObject().put("result", "ok")); } else { reportQueryError(message, res.cause()); } }); } else { reportQueryError(message, car.cause()); } }); }
switch (message.headers().get("action")) { case "all-pages": fetchAllPages(message); break; case "get-page": fetchPage(message);
break; case "create-page": createPage(message); break; case "save-page": savePage(message); break; case "delete-page": deletePage(message); break; default: message.fail(ErrorCodes.BAD_ACTION.ordinal(), "Bad action: " + action); } 0 If lots of actions…
@ProxyGen public interface WikiDatabaseService { // ( ...) @Fluent WikiDatabaseService
savePage(int id, String markdown, Handler<AsyncResult<Void >> resultHandler); @Fluent WikiDatabaseService deletePage(int id, Handler<AsyncResult<Void >> resultHandler); static WikiDatabaseService createProxy(Vertx vertx, String address) { return new WikiDatabaseServiceVertxEBProxy(vertx, address); } // ( ...) } Proxy + handler source code will be generated Parameters from a JSON document Handlers for replies Generated proxy
dbService = WikiDatabaseService.createProxy(vertx, "wikidb.queue"); private void pageDeletionHandler(RoutingContext context) { dbService.deletePage(Integer.valueOf(context.request().getParam("id")),
reply -> { if (reply.succeeded()) { context.response().setStatusCode(303); context.response().putHeader("Location", "/"); context.response().end(); } else { context.fail(reply.cause()); } }); }
Dealing with asynchronous events
foo.a(1, res1 -> { if (res1.succeeded()) { bar.b("abc", 1, res2
-> { if (res.succeeded()) { baz.c(res3 -> { dosomething(res1, res2, res3, res4 -> { // (...) }); }); } }); } }); “Callback hell”
Callbacks RxJava 1 + 2 Quasar (vertx-sync) Kotlin coroutines (core)
(codegen)
Reactive Programming with Vert.x and RxJava Kotlin
RxJava Data and events flows Organising transformation of data and
coordination of events Makes most sense with many sources of events
Push based subscribe ➊ ➋push Observer Observable
Iterable / Observable try { for (String item : it)
{ ➊ } ➌ } catch (Throwable e) { ➋ } observable.subscribe(item -> { ➊ // onNext }, error -> { ➋ // onError }, () -> { ➌ // onCompleted });
0 0..1 0..n Reactive Completable Maybe<T> Single<T> Observable<T> Flowable<T> Interactive
void T Iterable<T>
None
None
None
None
Rxified Handler<AsyncResult> void listen(int port, Handler<AsyncResult<HttpServer>> ar) Single<HttpServer> rxListen(int
port);
(demo) RxJava
Kotlin coroutines (and Vert.x)
Coroutines are computer-program components that generalise subroutines for non-preemptive multitasking,
by allowing multiple entry points for suspending and resuming execution at certain locations. “ ” — https://en.wikipedia.org/wiki/Coroutine
Suspending lambdas and functions (suspend keyword) Compiler work for suspending
functions (state machines…) Low-level library: kotlin.coroutines create / start / suspend / intrinsics sequence and iterator generators (think Python, Golo, etc) High-level library: kotlinx.coroutines core primitives (launch, async, select, delay, …) reactive, UI, CompletableFuture, etc Kotlin Coroutines
) Suspend ) Begin ) ) End Resume Coroutine life
cycle
Coroutines are confined to Vert.x event loop threads awaitResult<T> and
awaitEvent<T> Channels from/to Vert.x streams Integrates with the coroutine ecosystem Coroutines for Vert.x
(demo) Coroutines with and without Vert.x
Outro
Vert.x Awesome Vert.x Stack Vert.x Core
None
Unified end-to-end reactive model + ecosystem (not just APIs…) For
all kinds of distributed applications (even the small-scale ones) Flexible toolkit, not a framework (your needs, your call)
https: //youtu.be/ZkWsilpiSqw 1 Applications réactives avec Eclipse Vert.x 2 Building
Reactive Microservices in Java https: //goo.gl/ep6yB9 2 Guide to async programming with Vert.x for Java developers https: //goo.gl/AcWW3A 3 Kotlin Slack — #vertx