add postgresql listener
This commit is contained in:
parent
6127f11914
commit
c6e4c7e940
2 changed files with 54 additions and 0 deletions
|
@ -4,6 +4,7 @@ import org.xbib.jdbc.postgresql.Postgresql;
|
|||
module org.xbib.jdbc.postgresql {
|
||||
requires org.xbib.jdbc.query;
|
||||
requires java.sql;
|
||||
requires org.postgresql.jdbc;
|
||||
uses Flavor;
|
||||
exports org.xbib.jdbc.postgresql;
|
||||
provides Flavor with Postgresql;
|
||||
|
|
|
@ -0,0 +1,53 @@
|
|||
package org.xbib.jdbc.postgresql;
|
||||
|
||||
import org.postgresql.PGNotification;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Listener implements Runnable {
|
||||
|
||||
private final Connection connection;
|
||||
|
||||
private final org.postgresql.PGConnection pgConnection;
|
||||
|
||||
private final Consumer<PGNotification> notificationConsumer;
|
||||
|
||||
private final Consumer<Throwable> errorConsumer;
|
||||
|
||||
public Listener(Connection connection,
|
||||
Consumer<PGNotification> notificationConsumer,
|
||||
Consumer<Throwable> errorConsumer) throws SQLException {
|
||||
this.connection = connection;
|
||||
this.pgConnection = (org.postgresql.PGConnection) connection;
|
||||
this.errorConsumer = errorConsumer;
|
||||
this.notificationConsumer = notificationConsumer;
|
||||
try (Statement stmt = connection.createStatement()) {
|
||||
stmt.execute("LISTEN event");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
while (true) {
|
||||
try (Statement stmt = connection.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("SELECT 1")) {
|
||||
} catch (SQLException e) {
|
||||
errorConsumer.accept(e);
|
||||
}
|
||||
try {
|
||||
PGNotification[] notifications = pgConnection.getNotifications();
|
||||
if (notifications != null) {
|
||||
for (PGNotification notification : notifications) {
|
||||
notificationConsumer.accept(notification);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
errorConsumer.accept(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue