postgresql 创建listen notify .net core6.0监听连接

背景:数据库某张表定时有第三方更新到实时表里,收到数据更新以后,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\().GetConnectionString("LocalNpgsqlConnection"); using var conn = new NpgsqlConnection(connectionString); await conn.OpenAsync(stoppingToken); using var cmd = new NpgsqlCommand("listen data_changed", conn); cmd.ExecuteNonQuery(); conn.Notification += (sender, e) =\> { Console.WriteLine($"Received table update notification: {e.Payload}"); // 在这里执行相应的操作,处理接收到的通知 }; while (!stoppingToken.IsCancellationRequested) { using var transaction = conn.BeginTransaction(); await transaction.CommitAsync(); await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken); // 可以选择适当的延迟时间 } } } } startup.cs注册下服务 services.AddHostedService\(); psql 发送测试。 UPDATE "public"."river_area" SET "objectid" = 5 WHERE "gid" = 3; NOTIFY data_changed, 'Your notification payload here'; 测试通过

相关推荐
TDengine (老段)13 分钟前
TDengine 产品组件 taosX
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
沐伊~36 分钟前
mysql 安装
数据库·mysql
TimberWill38 分钟前
CONCAT函数使用中出现空指针异常问题分析
数据库
TDengine (老段)1 小时前
TDengine 字符串函数 CHAR_LENGTH 用户手册
大数据·数据库·时序数据库·tdengine·涛思数据
wind_one11 小时前
5.基础--SQL--DDL数据库操作
数据库·sql
TDengine (老段)1 小时前
TDengine 数学函数 CRC32 用户手册
java·大数据·数据库·sql·时序数据库·tdengine·1024程序员节
llxxyy卢1 小时前
SQL注入之二次、加解密、DNS等注入
数据库·sql
数据库学啊1 小时前
供暖季技术实战:益和热力用 TDengine 时序数据库破解热力数据处理难题
数据库·时序数据库·tdengine
SEO_juper1 小时前
搜索引擎索引权威指南:抓取、收录与排名的基础
数据库·搜索引擎·seo·数字营销
不剪发的Tony老师1 小时前
SQLite 3.51.0发布,新功能解读
数据库·sqlite