-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathCoreExamples.java
More file actions
598 lines (477 loc) · 17.4 KB
/
CoreExamples.java
File metadata and controls
598 lines (477 loc) · 17.4 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
* Copyright (c) 2011-2025 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package examples;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.dns.AddressResolverOptions;
import io.vertx.core.file.FileProps;
import io.vertx.core.file.FileSystem;
import io.vertx.core.http.*;
import io.vertx.core.internal.logging.Logger;
import io.vertx.core.internal.logging.LoggerFactory;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import io.vertx.core.spi.VertxMetricsFactory;
import io.vertx.core.spi.VertxTracerFactory;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.core.transport.Transport;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Created by tim on 08/01/15.
*/
public class CoreExamples {
public void example1() {
Vertx vertx = Vertx.vertx();
}
public void example2() {
Vertx vertx = Vertx.vertx(new VertxOptions().setWorkerPoolSize(40));
}
public void example3(HttpServerRequest request) {
request.response().putHeader("Content-Type", "text/plain").end("some text");
}
public void example4(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.putHeader("Content-Type", "text/plain");
response.end("some text");
}
public void example5(Vertx vertx) {
vertx.setPeriodic(1000, id -> {
// This handler will get called every second
System.out.println("timer fired!");
});
}
public void example6(HttpServer server) {
// Respond to each http request with "Hello World"
server.requestHandler(request -> {
// This handler will be called every time an HTTP request is received at the server
request.response().end("hello world!");
});
}
public void example7(Vertx vertx) {
vertx.executeBlocking(() -> {
// Call some blocking API that takes a significant amount of time to return
return someAPI.blockingMethod("hello");
})
.onSuccess(result -> System.out.println("The result is: " + result));
}
public void workerExecutor1(Vertx vertx) {
WorkerExecutor executor = vertx.createSharedWorkerExecutor("my-worker-pool");
executor.executeBlocking(() -> {
// Call some blocking API that takes a significant amount of time to return
return someAPI.blockingMethod("hello");
})
.onSuccess(result -> System.out.println("The result is: " + result));
}
public void workerExecutor2(WorkerExecutor executor) {
executor.close();
}
public void workerExecutor3(Vertx vertx) {
//
// 10 threads max
int poolSize = 10;
// 2 minutes
long maxExecuteTime = 2;
TimeUnit maxExecuteTimeUnit = TimeUnit.MINUTES;
WorkerExecutor executor = vertx.createSharedWorkerExecutor("my-worker-pool", poolSize, maxExecuteTime, maxExecuteTimeUnit);
}
BlockingAPI someAPI = new BlockingAPI();
class BlockingAPI {
String blockingMethod(String str) {
return str;
}
}
public void vertxBuilder(VertxOptions options, VertxMetricsFactory metricsFactory, VertxTracerFactory tracerFactory) {
Vertx vertx = Vertx.builder()
.with(options)
.withTracer(tracerFactory)
.withMetrics(metricsFactory)
.build();
}
public void clusteredVertxBuilder(VertxOptions options, ClusterManager clusterManager) {
Future<Vertx> vertx = Vertx.builder()
.with(options)
.withClusterManager(clusterManager)
.buildClustered();
}
public void exampleFuture1(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
Future<FileProps> future = fs.props("/my_file.txt");
future.onComplete((AsyncResult<FileProps> ar) -> {
if (ar.succeeded()) {
FileProps props = ar.result();
System.out.println("File size = " + props.size());
} else {
System.out.println("Failure: " + ar.cause().getMessage());
}
});
}
public void exampleFuture2(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
Future<FileProps> future = fs.props("/my_file.txt");
future
.onSuccess((FileProps fileProps) -> {
System.out.println("File size = " + fileProps.size());
})
.onFailure((Throwable e) -> {
System.out.println("Failure: " + e.getMessage());
});
}
public void exampleFuture3(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
fs.props("/my_file.txt")
.onSuccess(fileProps -> System.out.println("File size = " + fileProps.size()))
.onFailure(e -> System.out.println("Failure: " + e.getMessage()));
}
public void exampleFuture4(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
fs.props("/my_file.txt")
.onComplete(fileProps -> System.out.println("File size = " + fileProps.size()),
e -> System.out.println("Failure: " + e.getMessage()));
}
public void promiseCallbackOrder(Future<Void> future) {
future.onComplete(ar -> {
// Do something
});
future.onComplete(ar -> {
// May be invoked first
});
}
private void legacyGreetAsync(Handler<AsyncResult<String>> promise) {
}
public void exampleFutureComposition1(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
Future<Void> future = fs
.createFile("/foo")
.compose(v -> {
// When the file is created (fut1), execute this:
return fs.writeFile("/foo", Buffer.buffer());
})
.compose(v -> {
// When the file is written (fut2), execute this:
return fs.move("/foo", "/bar");
});
}
public void exampleFutureComposition2(Vertx vertx) {
FileSystem fs = vertx.fileSystem();
Future<Void> future = fs
.createFile("/foo")
// When the file is created (fut1), execute this:
.compose(v -> fs.writeFile("/foo", Buffer.buffer()))
// When the file is written (fut2), execute this:
.compose(v -> fs.move("/foo", "/bar"));
}
public Future<?> exampleFutureAll1(HttpServer httpServer, NetServer netServer) {
Future<HttpServer> httpServerFuture = httpServer.listen();
Future<NetServer> netServerFuture = netServer.listen();
return Future.all(httpServerFuture, netServerFuture)
.onFailure(e -> {
// At least one server failed
});
}
public void exampleFutureAll2(Future<?> future1, Future<?> future2, Future<?> future3) {
Future.all(Arrays.asList(future1, future2, future3));
}
public Future<String> exampleFutureAny1(Future<String> future1, Future<String> future2) {
return Future.any(future1, future2)
.map(result -> // At least one is succeeded
future1.succeeded() ? future1.result() : future2.result())
.onFailure(e -> {
// All failed
});
}
public void exampleFutureAny2(Future<?> f1, Future<?> f2, Future<?> f3) {
Future.any(Arrays.asList(f1, f2, f3));
}
public Future<String> exampleFutureJoin1(Future<String> future1, Future<String> future2, Future<String> future3) {
CompositeFuture compositeFuture = Future.join(future1, future2, future3);
return compositeFuture
.map(x -> {
// All completed, each is either succeeded or failed
return compositeFuture.<String>list().stream()
.filter(Objects::nonNull) // failed have null
.collect(Collectors.joining(", "));
});
}
public void exampleFutureJoin2(Future<?> future1, Future<?> future2, Future<?> future3) {
Future.join(Arrays.asList(future1, future2, future3));
}
class MyOrderProcessorVerticle extends VerticleBase {
}
public void simplestVerticle() {
class MyVerticle extends VerticleBase {
// Called when verticle is deployed
public Future<?> start() throws Exception {
return super.start();
}
// Optional - called when verticle is un-deployed
public Future<?> stop() throws Exception {
return super.stop();
}
}
}
public void httpServerVerticle() {
class MyVerticle extends VerticleBase {
private HttpServer server;
@Override
public Future<?> start() {
server = vertx.createHttpServer().requestHandler(req -> {
req.response()
.putHeader("content-type", "text/plain")
.end("Hello from Vert.x!");
});
// Now bind the server:
return server.listen(8080);
}
}
}
public void oneLinerVerticle(Vertx vertx) {
Deployable verticle = context -> vertx
.createHttpServer()
.requestHandler(req -> req.response()
.putHeader("content-type", "text/plain")
.end("Hello from Vert.x!"))
.listen(8080);
}
public void verticleContract() {
class MyVerticle extends AbstractVerticle {
@Override
public void start(Promise<Void> startPromise) throws Exception {
Future<String> future = bindService();
// Requires to write
future.onComplete(ar -> {
if (ar.succeeded()) {
startPromise.complete();
} else {
startPromise.fail(ar.cause());
}
});
// Or
future
.onSuccess(x -> startPromise.complete())
.onFailure(startPromise::fail);
// Or
future
.onComplete(x -> startPromise.complete(),
startPromise::fail);
// Or
future
.<Void>mapEmpty()
.onComplete(startPromise);
}
}
}
static Future<String> bindService() {
throw new UnsupportedOperationException();
}
public void example7_1(Vertx vertx) {
DeploymentOptions options = new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER);
vertx.deployVerticle(new MyOrderProcessorVerticle(), options);
}
public void example7_2(Vertx vertx) {
DeploymentOptions options = new DeploymentOptions().setThreadingModel(ThreadingModel.VIRTUAL_THREAD);
vertx.deployVerticle(new MyOrderProcessorVerticle(), options);
}
public void example8(Vertx vertx) {
VerticleBase myVerticle = new MyVerticle();
vertx.deployVerticle(myVerticle);
}
static class MyVerticle extends VerticleBase {
}
public void example9(Vertx vertx) {
// Deploy a Java verticle - the name is the fully qualified class name of the verticle class
vertx.deployVerticle("com.mycompany.MyOrderProcessorVerticle");
}
public Future<String> example10(Vertx vertx) {
return vertx
.deployVerticle(new MyOrderProcessorVerticle())
.onSuccess(deploymentID -> System.out.println("Deployment id is: " + deploymentID));
}
public void example11(Vertx vertx, String deploymentID) {
vertx.undeploy(deploymentID);
}
public void example12(Vertx vertx) {
DeploymentOptions options = new DeploymentOptions().setInstances(16);
vertx.deployVerticle(() -> new MyOrderProcessorVerticle(), options);
}
public void example13(Vertx vertx) {
JsonObject config = new JsonObject().put("name", "tim").put("directory", "/blah");
DeploymentOptions options = new DeploymentOptions().setConfig(config);
vertx.deployVerticle(new MyOrderProcessorVerticle(), options);
}
public void example15(Vertx vertx) {
long timerID = vertx.setTimer(1000, id -> {
System.out.println("And one second later this is printed");
});
System.out.println("First this is printed");
}
public void example16(Vertx vertx) {
long timerID = vertx.setPeriodic(1000, id -> {
System.out.println("And every second this is printed");
});
System.out.println("First this is printed");
}
public void example17(Vertx vertx, long timerID) {
vertx.cancelTimer(timerID);
}
public void timerExample(Vertx vertx) {
// Create a timer
Future<String> timer = vertx
.timer(10, TimeUnit.SECONDS)
.map(v -> "Success");
timer.onSuccess(value -> {
System.out.println("Timer fired: " + value);
});
timer.onFailure(cause -> {
System.out.println("Timer cancelled: " + cause.getMessage());
});
}
public void example18(String className, Exception exception) {
// Note -these classes are Java only
// You would normally maintain one static instance of Logger per Java class:
Logger logger = LoggerFactory.getLogger(className);
logger.info("something happened");
logger.error("oops!", exception);
}
public void retrieveContext(Vertx vertx) {
Context context = vertx.getOrCreateContext();
}
public void retrieveContextType(Vertx vertx) {
Context context = vertx.getOrCreateContext();
if (context.isEventLoopContext()) {
System.out.println("Context attached to Event Loop");
} else if (context.isWorkerContext()) {
System.out.println("Context attached to Worker Thread");
} else if (! Context.isOnVertxThread()) {
System.out.println("Context not attached to a thread managed by vert.x");
}
}
public void runInContext(Vertx vertx) {
vertx.getOrCreateContext().runOnContext( (v) -> {
System.out.println("This will be executed asynchronously in the same context");
});
}
public void runInContextWithData(Vertx vertx) {
final Context context = vertx.getOrCreateContext();
context.put("data", "hello");
context.runOnContext((v) -> {
String hello = context.get("data");
});
}
public void systemAndEnvProperties() {
System.getProperty("prop");
System.getenv("HOME");
}
public void configureDNSServers() {
Vertx vertx = Vertx.vertx(new VertxOptions().
setAddressResolverOptions(
new AddressResolverOptions().
addServer("192.168.0.1").
addServer("192.168.0.2:40000"))
);
}
public void configureHosts() {
Vertx vertx = Vertx.vertx(new VertxOptions().
setAddressResolverOptions(
new AddressResolverOptions().
setHostsPath("/path/to/hosts"))
);
}
public void configureSearchDomains() {
Vertx vertx = Vertx.vertx(new VertxOptions().
setAddressResolverOptions(
new AddressResolverOptions().addSearchDomain("foo.com").addSearchDomain("bar.com"))
);
}
public void deployVerticleWithDifferentWorkerPool(Vertx vertx) {
vertx.deployVerticle(new MyOrderProcessorVerticle(), new DeploymentOptions().setWorkerPoolName("the-specific-pool"));
}
public void configureNative() {
Vertx vertx = Vertx.vertx(new VertxOptions().
setPreferNativeTransport(true)
);
// True when native is available
boolean usingNative = vertx.isNativeTransportEnabled();
System.out.println("Running with native: " + usingNative);
}
public void configureTransport() {
// Use epoll/kqueue/io_uring native transport depending on OS
Transport transport = Transport.nativeTransport();
// Or use a very specific transport
transport = Transport.EPOLL;
Vertx vertx = Vertx.builder()
.withTransport(transport)
.build();
}
public void configureLinuxOptions(Vertx vertx, boolean fastOpen, boolean cork, boolean quickAck, boolean reusePort) {
// Available on Linux
vertx.createHttpServer(new HttpServerOptions()
.setTcpFastOpen(fastOpen)
.setTcpCork(cork)
.setTcpQuickAck(quickAck)
.setReusePort(reusePort)
);
}
public void configureBSDOptions(Vertx vertx, boolean reusePort) {
// Available on BSD
vertx.createHttpServer(new HttpServerOptions().setReusePort(reusePort));
}
public Future<NetServer> tcpServerWithDomainSockets(Vertx vertx) {
NetServer netServer = vertx.createNetServer();
// Only available when running on JDK16+, or using a native transport
SocketAddress address = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");
return netServer
.connectHandler(so -> {
// Handle application
})
.listen(address);
}
public Future<HttpServer> httpServerWithDomainSockets(Vertx vertx) {
HttpServer httpServer = vertx.createHttpServer();
// Only available when running on JDK16+, or using a native transport
SocketAddress address = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");
return httpServer
.requestHandler(req -> {
// Handle application
})
.listen(address);
}
public Future<NetSocket> tcpClientWithDomainSockets(Vertx vertx) {
NetClient netClient = vertx.createNetClient();
// Only available when running on JDK16+, or using a native transport
SocketAddress addr = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");
// Connect to the server
return netClient
.connect(addr);
}
private Future<Void> process(Buffer buffer, String parameter) {
return Future.succeededFuture();
}
public Future<Void> httpClientWithDomainSockets(Vertx vertx) {
HttpClient httpClient = vertx.createHttpClient();
// Only available when running on JDK16+, or using a native transport
SocketAddress addr = SocketAddress.domainSocketAddress("/var/tmp/myservice.sock");
// Send request to the server
return httpClient.request(new RequestOptions()
.setServer(addr)
.setHost("localhost")
.setPort(8080)
.setURI("/"))
.compose(request -> request.send())
.compose(HttpClientResponse::body)
.compose(buffer -> process(buffer, "some parameter")); // Process response
}
}