NOTIFY 是一个实用命令,用于向连接到同一数据库的其他会话发送通知,这些会话正在监听由 LISTEN 命令指定的频道。
NOTIFY 一直存在于 PostgreSQL 中。
用法
通过执行 NOTIFY ,或者(自 PostgreSQL 9.0 起) channelNOTIFY ,通知将被传递给所有监听该频道的会话(使用 channel, 'message'LISTEN 命令)。监听的会话将在下次执行查询时收到通知。通知可以选择包含消息。
通知和事务
NOTIFY 在事务的上下文中运行。通知将在事务提交后才会传输,如果事务回滚则不会发送。
pg_notify()
函数 pg_notify() 提供了与 NOTIFY 相同的功能,并允许使用来自表或表达式的值来执行通知。
统计信息
从 PostgreSQL 13 开始,pg_stat_slru 返回的 Notify 记录包含有关 NOTIFY 用法的统计信息。
变更历史
- PostgreSQL 9.0
- (提交 d1e02722)
示例
基本 NOTIFY 用法示例
postgres=# NOTIFY foo; NOTIFY
这会向所有监听频道 foo 的会话发送通知,这些会话将在执行查询时收到。
postgres=# LISTEN foo; LISTEN postgres=# SELECT pg_backend_pid(); pg_backend_pid ---------------- 23711 (1 row) Asynchronous notification "foo" received from server process with PID 20679.
如果一个会话监听某个频道,它也会收到自己的通知。
postgres=# LISTEN foo; LISTEN postgres=# NOTIFY foo; NOTIFY Asynchronous notification "foo" received from server process with PID 20679. postgres=# NOTIFY foo;
为了简化后续示例,它们将显示为会话监听自己的频道。
可以使用最多 7999 字节的可选消息与通知一起传递。
postgres=# NOTIFY foo, 'hello world'; NOTIFY Asynchronous notification "foo" with payload "hello world" received from server process with PID 20679.
消息必须指定为字符串(不能为 NULL),但如果字符串为空,NOTIFY 的行为就好像没有提供消息一样。
postgres=# NOTIFY foo, NULL;
ERROR: syntax error at or near "NULL"
LINE 1: NOTIFY foo, NULL;
^
postgres=# NOTIFY foo, '';
NOTIFY
Asynchronous notification "foo" received from server process with PID 20679.
如果字符串超过最大长度(默认 7999 字节),则会引发错误。
postgres=# NOTIFY 'foo', '... very long message ...';
ERROR: payload string too long
消息字符串必须作为字面量提供;无法从表达式(例如,通过连接或作为函数的结果)生成它们。
postgres=# NOTIFY foo, 'foo' || 'bar';
ERROR: syntax error at or near "||"
LINE 1: NOTIFY foo, 'foo' || 'bar';
^
postgres=# NOTIFY foo, REPEAT('bar', 2);
ERROR: syntax error at or near "REPEAT"
LINE 1: NOTIFY foo, REPEAT('foo', 2);
^
但是,这可以通过 pg_notify() 来实现。
通知仅在事务提交后发送。
postgres=# BEGIN; BEGIN postgres=*# NOTIFY foo, 'hello world'; NOTIFY postgres=*# COMMIT; COMMIT Asynchronous notification "foo" with payload "hello world" received from server process with PID 20679.
如果事务回滚,则不发送通知。
postgres=# BEGIN; BEGIN postgres=*# NOTIFY foo, 'hello world'; NOTIFY postgres=*# ROLLBACK ; ROLLBACK
参考资料
- PostgreSQL 文档: NOTIFY
另请参阅
反馈
在此处 提交关于“NOTIFY”的任何评论、建议或更正。