pg_notify()

用于向其他会话发送通知的函数

pg_notify() 是一个系统函数,用于向连接到同一数据库并监听指定通道的其他会话发送通知,该通道使用 LISTEN 命令指定。

pg_notify() 添加于 PostgreSQL 9.0

用法

pg_notify (text, text) → void

pg_notify() 提供了等效于 NOTIFY 命令的功能,但允许从表、表达式或其他数据源派生通道名称(第一个参数)和(可选)消息(第二个参数)。它还允许使用单个查询发送多个通知。

有关更多详细信息,请参阅 NOTIFY

变更历史

示例

基本的 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 fooNOTIFY 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.

分类

异步通知系统函数

参见

NOTIFYpg_listening_channels()

反馈

提交关于“pg_notify()”的任何评论、建议或更正 此处