-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
SqlClientExample.java
75 lines (67 loc) · 2.44 KB
/
SqlClientExample.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package io.vertx.example.sqlclient.streaming;
import io.vertx.core.*;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.sqlclient.*;
import org.testcontainers.containers.PostgreSQLContainer;
/*
* @author <a href="mailto:[email protected]">Paulo Lopes</a>
*/
public class SqlClientExample extends VerticleBase {
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>();
postgres.start();
PgConnectOptions options = new PgConnectOptions()
.setPort(postgres.getMappedPort(5432))
.setHost(postgres.getContainerIpAddress())
.setDatabase(postgres.getDatabaseName())
.setUser(postgres.getUsername())
.setPassword(postgres.getPassword());
// Uncomment for MySQL
// MySQLContainer<?> mysql = new MySQLContainer<>();
// mysql.start();
// MySQLConnectOptions options = new MySQLConnectOptions()
// .setPort(mysql.getMappedPort(3306))
// .setHost(mysql.getContainerIpAddress())
// .setDatabase(mysql.getDatabaseName())
// .setUser(mysql.getUsername())
// .setPassword(mysql.getPassword());
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new SqlClientExample(options)); }
private final SqlConnectOptions options;
private Pool pool;
public SqlClientExample(SqlConnectOptions options) {
this.options = options;
}
@Override
public Future<?> start() {
pool = Pool.pool(vertx, options, new PoolOptions().setMaxSize(4));
return pool.withConnection(connection -> {
// create a test table
return connection
.query("create table test(id int primary key, name varchar(255))")
.execute()
.compose(v -> {
// insert some test data
return connection
.query("insert into test values (1, 'Hello'), (2, 'World')")
.execute();
})
.compose(v -> connection
.prepare("select * from test")
.compose(ps -> {
RowStream<Row> stream = ps.createStream(50);
Promise<Void> promise = Promise.promise();
stream
.exceptionHandler(promise::fail)
.endHandler(promise::complete)
.handler(row -> System.out.println("row = " + row.toJson()));
return promise
.future()
.eventually(ps::close);
}));
}).onSuccess(ar -> {
System.out.println("done");
});
}
}