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()"的评论、建议或更正 在此