From what I can tell, the JDBC drivers for LISTEN/NOTIFY in Java do NOT support true event-driven notifications. You have to poll the database every so often to see if there's a new notification.
What options do I have in Java (possibly something other than JDBC?), if any, to get notifications asynchronously in a true event-driven manner without polling?
The current version of the driver should be compatible with PostgreSQL 8.2 and higher using the version 3.0 of the PostgreSQL protocol, and it's compatible with Java 8 (JDBC 4.2) and above.
The NOTIFY command sends a notification event together with an optional “payload” string to each client application that has previously executed LISTEN channel for the specified channel name in the current database. Notifications are visible to all users.
PostgreSQL offers an asynchronous Publish-Subscribe functionality in the form of the LISTEN and NOTIFY commands. A client registers its interest in a particular channel (a.k.a. topic or event) with the LISTEN command (and can stop listening with the UNLISTEN command).
Use the pgjdbc-ng driver.
http://impossibl.github.io/pgjdbc-ng/
It supports async notifications, without polling. I have used it successfully.
See https://database-patterns.blogspot.com/2014/04/postgresql-nofify-websocket-spring-mvc.html
Oleg has a nice example answer as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With