|
| 1 | +package com.zetcode; |
| 2 | + |
| 3 | +import com.github.jasync.sql.db.Connection; |
| 4 | +import com.github.jasync.sql.db.ConnectionPoolConfigurationBuilder; |
| 5 | +import com.github.jasync.sql.db.QueryResult; |
| 6 | +import com.github.jasync.sql.db.postgresql.PostgreSQLConnectionBuilder; |
| 7 | +import io.javalin.Javalin; |
| 8 | +import org.slf4j.Logger; |
| 9 | +import org.slf4j.LoggerFactory; |
| 10 | + |
| 11 | +import java.util.concurrent.CompletableFuture; |
| 12 | +import java.util.concurrent.TimeUnit; |
| 13 | + |
| 14 | +// example for asynchronous database access with Jasync and Javalin |
| 15 | + |
| 16 | +public class AsyncDatabase { |
| 17 | + |
| 18 | + private static final Logger logger = LoggerFactory.getLogger(AsyncDatabase.class); |
| 19 | + |
| 20 | + public static void main(String[] args) { |
| 21 | + |
| 22 | + var config = new ConnectionPoolConfigurationBuilder(); |
| 23 | + config.setUsername("postgres"); |
| 24 | + config.setPassword("s$cret"); |
| 25 | + config.setDatabase("postgres"); |
| 26 | + config.setMaxActiveConnections(100); |
| 27 | + config.setMaxIdleTime(TimeUnit.MINUTES.toMillis(15)); |
| 28 | + config.setMaxPendingQueries(10000); |
| 29 | + config.setConnectionValidationInterval(TimeUnit.SECONDS.toMillis(30)); |
| 30 | + |
| 31 | + Connection connection = PostgreSQLConnectionBuilder.createConnectionPool(config); |
| 32 | + |
| 33 | + Javalin app = Javalin.create() |
| 34 | + .events(event -> { |
| 35 | + event.serverStarting(() -> { |
| 36 | + logger.info("--- SERVER STARTING!"); |
| 37 | + connection.connect().get(); |
| 38 | + logger.info("--- connection STARTED!"); |
| 39 | + }); |
| 40 | + event.serverStopping(() -> { |
| 41 | + logger.info("--- SERVER STOPPING!"); |
| 42 | + connection.disconnect().get(); |
| 43 | + logger.info("--- connection STOPPED!"); |
| 44 | + }); |
| 45 | + }) |
| 46 | + .start(7000); |
| 47 | + |
| 48 | + app.get("/", (ctx) -> { |
| 49 | + |
| 50 | + final CompletableFuture<QueryResult> queryResultCompletableFuture = |
| 51 | + connection.sendPreparedStatement("select 3+6"); |
| 52 | + |
| 53 | + ctx.result( |
| 54 | + queryResultCompletableFuture |
| 55 | + .thenApply((t) -> "got result: " + t.getRows().get(0).get(0)) |
| 56 | + ); |
| 57 | + }); |
| 58 | + } |
| 59 | +} |
0 commit comments