简体   繁体   English

Node-RED实时监听PostgreSQL

[英]Node-RED listen PostgreSQL in real-time

I need to listen PostgreSQL on changes in real-time with Node-RED. 我需要通过Node-RED实时监听PostgreSQL的变化。 How can I do this? 我怎样才能做到这一点?

I created trigger on new record in the table and notify this to 'changes' channel. 我在表中的新记录上创建了触发器,并将其通知“更改”通道。

CREATE FUNCTION notify_trigger() RETURNS trigger AS $$
DECLARE
BEGIN
  PERFORM pg_notify('changes', TG_TABLE_NAME || ',id,' || NEW.id );
  RETURN new;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER watched_table_trigger AFTER INSERT ON users
FOR EACH ROW EXECUTE PROCEDURE notify_trigger();

But I don't know how to listen it from Node-RED. 但是我不知道如何从Node-RED收听它。 Could you help me please? 请问你能帮帮我吗? Maybe I can do it differently? 也许我可以做不同的事情?

Have a look at this previous SO question: 看一下之前的SO问题:

MQTT Client subscribe to PostgreSQL DB Changes MQTT客户端订阅PostgreSQL数据库更改

It looks like Postgress supports Python based triggers which could be used to send a MQTT message which Node-RED could easily subscriber to. 看起来Postgress支持基于Python的触发器,该触发器可用于发送MQTT消息,Node-RED可以轻松订阅该消息。

I found a good solution for yourself with WebSocket. 我用WebSocket为自己找到了一个很好的解决方案。 Look at example below: 看下面的例子:

在此处输入图片说明

var pg = global.get('pg'),
    WebSocket = global.get('ws'),
    config = {
        user: 'user',
        password: 'user',
        host: 'somehost',
        port: 1234,
        database: 'somedb'
    },
    client = new pg.Client(config);

client.connect(function(err) {
    if (err) node.error(err);

    client.on('notification', function(msg) {
        node.send(msg);
    });

    var query = client.query("LISTEN changes");
});

delete msg._session;
return msg;

Post your solution, I really want to know more ways to solve this. 发布您的解决方案后,我真的很想知道更多解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM