Database notifications

Using a database queue for distributing CPU intensive workload might be a good idea. But there is one problem. How consumers find that there is some work to be done? Of course, we can repeatedly check the database queue, but it consumes database resources. There is one simple solution. Database notifications.

After putting work to the queue, we can notify our workers via database (PostgreSQL syntax):

NOTIFY my_notification;

You can find more information in PostgreSQL documentation. Let’s focus on Java now.

Send event

pgNotifyService.notify("myEvent", "myEventParameter");

Listener

The listeners may be running on another machine in the network. Try to start several backends simultaneously. Notifications will be shared between backends 🙂

private final PgCallback eventListener = (eventParameter) -> {
 System.out.println("Event received, parameter: " + eventParameter);
};

Complete Java Example

package com.goodbackend;

import com.goodbackend.notify.PgCallback;
import com.goodbackend.notify.PgNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@SpringBootApplication
public class ExampleNotify {

@Autowired
private PgNotifyService pgNotifyService;

private final String EVENT_NAME = "myEvent";

private final PgCallback eventListener = (eventParameter) -> {
//this code can be run in different java backend, different machine over network
System.out.println("Event received with parameter: " + eventParameter);
};

@EventListener(ApplicationReadyEvent.class)
public void start() {
//send event notification. All java backend connected to the same database will receive this notification
pgNotifyService.notify("myEvent", "myEventParameter");
System.out.println("Event sent..");
}

@PostConstruct
private void init() {
//register listener
pgNotifyService.addServiceListener(EVENT_NAME,eventListener);
}

@PreDestroy
private void destroy() {
//unregister listener
pgNotifyService.removeServiceListener(eventListener);
}

public static void main(final String[] args) {
SpringApplication.run(ExampleNotify.class, args);
}

}

Here you can download complete PostgreSQL java notification implementation.

One thought on “Database notifications”

Leave a Reply