我在
Postgresql 9.1数据库上有一个“文章”表和一个通知每个插入的通道的触发器.
@H_404_1@我想创建一个node.js脚本来捕获这些插入并使用Socket.io将通知推送到连接的客户端.到目前为止,我正在使用node-postgres模块LISTEN到通道,但似乎LISTEN查询在大约10-15秒后超时并停止捕获插入.我可以在超时发生时查询新的监听,但我不确定如何正确实现延续.
@H_404_1@这是我的postgresql通知程序:
CREATE FUNCTION article_insert_notify() RETURNS trigger AS $$ BEGIN NOTIFY "article_watcher"; RETURN NULL; END; $$LANGUAGE plpgsql;@H_404_1@触发:
CREATE TRIGGER article_insert_trigger AFTER INSERT ON article FOR EACH ROW EXECUTE PROCEDURE article_insert_notify();@H_404_1@而node.js代码:
var pg = require ('pg'),pgConnection = "postgres://user:pass@localhost/db" pg.connect(pgConnection,function(err,client) { client.query('LISTEN "article_watcher"'); client.on('notification',function(data) { console.log(data.payload); }); });@H_404_1@如何确保全职LISTEN或如何捕获这些超时以重新发出侦听查询?或者,node-postgres以外的模块可能提供更合适的工具吗?
我在node-postgres repo上得到了我的问题的答案.引用Brianc:
原文链接:https://www.f2er.com/postgresql/191631.html@H_404_1@pg.connect is use to create pooled connections. Using a connection@H_404_1@在这种情况下,正确的监听方式是使用独立客户端:
pool connection for listen events really isn’t supported or a good
idea though.
[…]
To ‘listen’ a connection by definition must stay open permanently. For
a connection to stay open permanently it can never be returned to the
connection pool.
var pg = require ('pg'),pgConnectionString = "postgres://user:pass@localhost/db"; var client = new pg.Client(pgConnectionString); client.connect(); client.query('LISTEN "article_watcher"'); client.on('notification',function(data) { console.log(data.payload); });