如何正确监听来自node.js的postgresql通知

Mic*_*ael 6 postgresql listen notify node.js pg-notify

目标:
当一条新记录插入到特定的 PostgreSQL 表中时,我希望 PostgreSQL 通知我的 Node.js Web 应用程序,以便它可以启动对外部服务的 API 调用。

据我了解,基本步骤是:

  1. 建立一个 PostgreSQL 触发器函数来执行 pg_notify() 方法。
  2. 建立一个PostgreSQL触发器,在表插入后执行触发器函数。
  3. 在 Node.js 中建立一种机制来监听特定于通道的 PostgreSQL 通知。

这是我对每一步的尝试:

  1. notification_app_after_table_insert.pgsql中的触发函数

    CREATE OR REPLACE FUNCTION notify_app_after_table_insert()
    RETURNS TRIGGER AS
    $BODY$
        BEGIN
            PERFORM pg_notify('channel', row_to_json(NEW)::text);
            RETURN new;
        END;
    $BODY$
    LANGUAGE plpgsql
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在trigger_notify_app_after_table_insert.sql中触发

    CREATE TRIGGER trigger_notify_app_after_table_insert
    AFTER INSERT
    ON table
    FOR EACH ROW
    EXECUTE PROCEDURE notify_app_after_table_insert();
    
    Run Code Online (Sandbox Code Playgroud)
  3. index.js 中的侦听器机制(在我的网络应用程序的后端内)

    //tools
    const express = require('express');
    const app = express();
    const cors = require('cors');
    const bodyParser = require('body-parser');
    const port = 3001;
    const pool = require('./db'); //stores my postgresql credentials
    
    // Middleware
    app.use(cors())
    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({extended: true}))
    
    // Apply app.listen notification to console.log
    app.listen(port, () => {
        console.log(`App running on port ${port}.`)
    })
    
    // Apply channel-specific listener mechanism
    pool.connect(function(err, client, done) {
        if(err) {
            console.log(err);
        }
        client.on('notification', function(msg) {
            console.log(msg);
        })
        client.query("LISTEN channel");
        done();
    });
    
    Run Code Online (Sandbox Code Playgroud)

问题:
当后端 Web 应用程序服务器正在运行并且新记录插入到数据库表中时,我希望在我的 Web 应用程序的终端中看到一条通知消息,但什么也没有出现。我怀疑问题出在index.js的最后一个代码块中,但无法隔离它。

关于如何在index.js中正确接收通知有什么建议吗?提前致谢。

小智 0

我认为这是因为秩序。像这样写:

client.query("LISTEN channel");
client.on('notification', function(msg) {
  console.log(msg);
})
Run Code Online (Sandbox Code Playgroud)

对我来说,首先查询 LISTEN 是有效的。