pg_notify() 是一个系统函数,用于向连接到同一数据库并使用 LISTEN 命令监听的频道发送通知到其他会话。
pg_notify() 是在 PostgreSQL 9.0 中添加的。
用法
pg_notify (text,text) →void
pg_notify() 提供了与 NOTIFY 命令等效的功能,但允许频道名称(第一个参数)和(可选的)消息(第二个参数)从表、表达式或其他数据源派生。它还允许使用单个查询发送多个通知。
有关更多详细信息,请参阅 NOTIFY。
变更历史
- PostgreSQL 9.0
- 添加于(提交 d1e02722)
示例
基本的 pg_notify() 用法示例(为简化起见,显示监听相同频道的会话)
postgres=# LISTEN foo; LISTEN postgres=# SELECT pg_notify('foo', 'hello world'); pg_notify ----------- (1 row) Asynchronous notification "foo" with payload "hello world" received from server process with PID 4145118.
这等同于执行 NOTIFY 'foo', 'hello world'。
如果消息指定为 NULL 或 ''(空字符串),则通知将在没有消息的情况下发送。
postgres=# LISTEN foo;
LISTEN
postgres=# LISTEN bar;
LISTEN
postgres=# SELECT pg_notify('foo', NULL), pg_notify('bar', '');
pg_notify | pg_notify
-----------+-----------
|
(1 row)
Asynchronous notification "foo" received from server process with PID 4145118.
Asynchronous notification "bar" received from server process with PID 4145118.
上述函数调用等同于在事务中执行 NOTIFY foo 和 NOTIFY bar。
发送从表中生成的消息
postgres=# CREATE TABLE notifications(channel NAME NOT NULL, message TEXT);
CREATE TABLE
postgres=# INSERT INTO notifications VALUES
('foo', 'bar'),
('foo', 'the date is ' || current_date);
INSERT 0 2
postgres=# SELECT pg_notify(channel, message) FROM notifications;
pg_notify
-----------
(2 rows)
Asynchronous notification "foo" with payload "bar" received from server process with PID 4154810.
Asynchronous notification "foo" with payload "the date is 2021-06-18" received from server process with PID 4154810.
参考资料
- PostgreSQL 文档: pg_notify
