Is there a proper way of triggering an event from my PostgreSQL database upon insert/update on a certain table that sends a notification to a separate HTTP server?
For a standard REST API application, we mostly interact with the DB unidirectionally. However, if the backend relies on a certain field value on a certain table from the DB, then it would make sense for the DB to send the data to the backend server, instead of the backend repeatedly polling the DB table for any changes which keeps the DB unnecessarily occupied.
Is there a better or standard approach to this?
2
Answers
That’s what
LISTEN
/NOTIFY
is for. The application that should be notified connects to the database, issuesLISTEN channel_name
, then waits for data to arrive on the network socket. The trigger runsNOTIFY channel_name
, which sends a message to the waiting session.You can use SQL Dependency and SignalR like below:
First you have to register in sql dependency on change event handler.
After that you have to make a signalR connection in your application and the event which is being generated by signalR employee register class that is by the method which is _context.Clients.All.SendAsync("refreshEmployees"), On change of refreshEmployees you have to fetch the updated data.
Here is the reference video which I referred:
SignalR Part1
SignalR Part2