[英]Is there a way to notify backend server from a postgreSQL database on some trigger?
是否有一種正確的方法可以在插入/更新某個表時從我的 PostgreSQL 數據庫觸發事件,該表會向單獨的 HTTP 服務器發送通知? 對於標准的 REST API 應用程序,我們主要與數據庫進行單向交互。 但是,如果后端依賴於數據庫中某個表的某個字段值,那么數據庫將數據發送到后端服務器是有意義的,而不是后端重復輪詢數據庫表以獲取保持不變的任何更改數據庫不必要地占用。
有更好的或標准的方法嗎?
這就是LISTEN
/ NOTIFY
的用途。 應通知的應用程序連接到數據庫,發出LISTEN channel_name
,然后等待數據到達網絡套接字。 觸發器運行NOTIFY channel_name
,它向等待會話發送一條消息。
您可以像下面這樣使用 SQL 依賴項和 SignalR: 首先,您必須在 sql 中注冊對更改事件處理程序的依賴項。
public List<Employee> GetAllEmployees()
{
var employees = new List<Employee>();
using(SqlConnection conn = new SqlConnection(connectionString)){
conn.Open();
SqlDependency.Start(connectionString);
string commandText = "select Id, Name, Age from dbo.Employees";
SqlCommand cmd = new SqlCommand(commandText,conn);
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange+=new OnChangeEventHandler(dbChangeNotification); // Register into onChange Event
var reader = cmd.ExecuteReader();
while(reader.Read()){
var employee = new Employee{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
Age = Convert.ToInt32(reader["Age"])
};
employees.Add(employee);
}
}
return employees;
}
private void dbChangeNotification(object sender, SqlNotificationEventArgs e)
{
_context.Clients.All.SendAsync("refreshEmployees");
}
之后,您必須在您的應用程序中建立 signalR 連接,並通過 _context.Clients.All.SendAsync("refreshEmployees") 方法生成由 signalR 員工注冊 class 生成的事件,在更改 refreshEmployees 時獲取更新的數據。
這是我引用的參考視頻: SignalR Part1 SignalR Part2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.