背景:数据库某张表定时有第三方更新到实时表里,收到数据更新以后,WEBSOCKET发送前端
-- 创建一个发送通知的函数
CREATE OR REPLACE FUNCTION notify_event(event_name text) RETURNS void AS $$
BEGIN
PERFORM pg_notify(event_name, '');
END;
LANGUAGE plpgsql; -- 创建一个触发器,在数据变化时调用通知函数 CREATE OR REPLACE FUNCTION notify_trigger() RETURNS trigger AS
BEGIN
PERFORM notify_event('data_changed');
RETURN NEW;
END;
LANGUAGE plpgsql;
-- 在需要监听的表上创建触发器
CREATE TRIGGER data_change_trigger
AFTER INSERT OR UPDATE OR DELETE ON river_area
FOR EACH ROW
EXECUTE FUNCTION notify_trigger();
.net core创建一个后台运行服务
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Npgsql;
namespace Pipe.BLL
{
public class TableUpdateListenerService : BackgroundService
{
private readonly IServiceProvider _services;
public TableUpdateListenerService(IServiceProvider services)
{
_services = services;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _services.CreateScope();
var serviceProvider = scope.ServiceProvider;
var connectionString = serviceProvider.GetRequiredService\