LISTEN 是一个实用命令,它将当前会话注册为命名通道的监听器。
LISTEN 始终存在于 PostgreSQL 中。
用法
命名通道必须是有效的 SQL 标识符。
一旦执行 LISTEN,下次执行命令时就会收到来自另一个会话的任何待处理通知。
函数 pg_listening_channels() 返回一个当前会话正在监听的所有通道的列表。
执行 UNLISTEN 来停止监听命名通道。channelname
LISTEN 和事务
LISTEN 在事务的上下文中运行,并且只有在事务提交后才会生效。如果事务被回滚,该命令将无效。
变更历史
- PostgreSQL 9.0
- 将进程间消息系统转换为基于内存的队列(提交 d1e02722)
示例
LISTEN 的基本用法示例
postgres=# LISTEN foo; LISTEN
如果 NOTIFY 从另一个会话执行,将在处理下一个命令后收到通知
postgres=# CHECKPOINT; CHECKPOINT Asynchronous notification "foo" received from server process with PID 14161.
从 PostgreSQL 9.0 开始,通知可以包含可选的载荷
postgres=# SELECT 1;
?column?
----------
1
(1 row)
Asynchronous notification "foo" with payload "bar" received from server process with PID 14161.
可能会收到多条消息
postgres=# CHECKPOINT ; CHECKPOINT Asynchronous notification "foo" with payload "bar" received from server process with PID 14161. Asynchronous notification "bar" with payload "foo" received from server process with PID 14161.
在事务中使用 LISTEN
postgres=# BEGIN; BEGIN postgres=*# LISTEN foo; LISTEN postgres=*# SELECT * FROM pg_listening_channels(); pg_listening_channels ----------------------- (0 rows) postgres=*# commit; COMMIT postgres=# SELECT * FROM pg_listening_channels(); pg_listening_channels ----------------------- foo (1 row)
如果事务被回滚,会话将不会监听命名通道(除非它在事务开始前已经注册)
postgres=# SELECT * FROM pg_listening_channels(); pg_listening_channels ----------------------- foo (1 row) postgres=# BEGIN; BEGIN postgres=*# LISTEN bar; LISTEN postgres=*# LISTEN foo; LISTEN postgres=*# ROLLBACK ; ROLLBACK postgres=# SELECT * FROM pg_listening_channels(); pg_listening_channels ----------------------- foo (1 row)
通道名称必须是一个有效的 SQL 标识符,最多 63 个(NAMEDATALEN)字符(多余的字符将被截断)
postgres=# LISTEN 123; ERROR: syntax error at or near "123" LINE 1: LISTEN 123; postgres=# LISTEN ABCD012345678901234567890123456789012345678901234567890123456789; NOTICE: identifier "abcd012345678901234567890123456789012345678901234567890123456789" will be truncated to "abcd01234567890123456789012345678901234567890123456789012345678" LISTEN
参考资料
- PostgreSQL 文档: LISTEN
