Reputation: 1
I'm trying to set up NotificationListener using HikariDataSource and PGConnection (i'm using postgresql in my app), however I have a problem wrapping a HikariDataSource in PGConnection. Firt I tried to do it using a separate class with connection to the database and PGDataSource instead of Hikari (one class for all databse operations - using Hikari, one class for notification listener only), but the problem is that they're separate sessions and one session doesn't see the listening channel set in the other session.
So now I'm trying to add notification listening to my main DBconnection class, which uses HikariCP.
Here is my DataBaseconnection
class and what I tried to do:
public class DataBaseConnection {
private static HikariConfig config = new HikariConfig();
private static HikariDataSource dataSource;
public DataBaseConnection() {
}
static{
config.setJdbcUrl("jdbc:postgresql://localhost:5432/db_name");
config.setUsername("user");
config.setPassword("password");
dataSource = new HikariDataSource(config);
try(Connection connection = dataSource.getConnection()){
Statement stmt = connection.createStatement();
stmt.execute("LISTEN trigger_channel");
PGNotificationListener listener = new PGNotificationListener() {
@Override
public void notification(int processId, String channelName, String payload) {
System.out.println("Received notification: " + processId + ", " + channelName + ", " + payload);
}
};
PGConnection PGconn = dataSource.getConnection().unwrap(PGConnection.class);
PGconn.addNotificationListener(listener);
} catch(Exception e){
e.printStackTrace();
}
}
Below are different types of errors I receive when trying to cast my connection to PGConnection: -Cannot unwrap to com.impossibl.postgres.api.jdbc.PGConnection - for version above
-class com.zaxxer.hikari.pool.HikariProxyConnection cannot be cast to class com.impossibl.postgres.api.jdbc.PGConnection (com.zaxxer.hikari.pool.HikariProxyConnection is in module [email protected] of loader 'app'; com.impossibl.postgres.api.jdbc.PGConnection is in module [email protected] of loader 'app') - for version below:
((PGConnection) connection).addNotificationListener(listener);
Is there a correct way to use NotificationListener using HikariCP to make it work? I will be grateful for any advices.
Upvotes: 0
Views: 101