How to Implement a Db Listener in Java

How to make a database listener with java?

This is what LISTEN/NOTIFY was created for.

The only drawback is that you will need to have some kind of background thread that polls the database on a regular basis to see if any notifications are available.

You can also use the code from the Postgres Wiki to have a starting point

Implementing Database Listener

As @a_horse_with_no_name points out, PostgreSQL supports asynchronous notification channels for just this purpose.

You should create a trigger, probably in plpgsql, on the table(s) you wish to monitor. This trigger fires a NOTIFY when the table changes, optionally including the changed data its self.

The application LISTENs on the notification channel(s) and processes any asynchronous notifications it receives.

Note that it's valid to send an empty query, and you should do that instead of SELECT 1. e.g.:

stmt.execute("");

IIRC even that's optional if you're not using SSL, there's a way to poll purely client side. I don't remember what it is, though, so that's not real helpful.

You can determine exactly what changed by using a trigger-maintained change list table, or by using payloads on your notifications. Or you can simply re-read the whole table if it's small.



Related Topics



Leave a reply



Submit