略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: pg_get_notify

2024-12-22

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_notifyPing 数据库连接

说明

pg_get_notify(resource $connection, int $result_type = ?): array

pg_get_notify() 取得 SQL 命令 NOTIFY 发送的通告消息。要接收通告消息,必须发送 SQL 命令 LISTEN。如果连接中有通告消息,则数组包含消息名并且返回后端的 PID。如果没有消息则返回 false

参见 pg_get_pid()

示例 #1 PostgreSQL NOTIFY 消息

<?php 
$conn 
pg_pconnect("dbname=publisher");
if (!
$conn) {
    echo 
"An error occured.\n";
    exit;
}

// Listen 'author_updated' message from other processes
pq_query($conn'LISTEN author_updated;');
$notify pg_get_notify($conn);
if (!
$notify)
    print(
"No messages\n");
else
    
print_r($notify);
?>
add a noteadd a note

User Contributed Notes 2 notes

up
5
glococo at gmail dot com
5 years ago
Instant yet Simple PHP notification with HTML5 Server-Sent Events

sse.php
<?php
$dbconn
= new PDO("pgsql:host=localhost;dbname=mydb", "pduser", "userpass");
$dbconn->exec('LISTEN "channel_name"');   // those doublequotes are very important

header("X-Accel-Buffering: no"); // disable ngnix webServer buffering
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
ob_end_flush();  // close PHP output buffering
$inc=0;

while (
1) {
 
$result = "";
 
// wait for one Notify 10seconds instead of using sleep(10)
 
$result = $dbconn->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);

  if (
$result ) {
        echo
"id: $inc\ndata: ".stripslashes(json_encode($result))."\n\n";
       
$inc++;
  }

 
flush();
}
?>

Tested with HTML+JS sample file from Mozilla web site (ssedemo.php)
up
0
david at frankieandshadow dot com
1 year ago
It appears that pg_get_notify does not distinguish between no message waiting and a failure when checking - both seem to return FALSE.

I had to add a pg_check_connection(...) before pg_get_notify to check the connection is still alive (it's quite likely to be a long-standing connection with pg_get_notify as you'll be polling waiting for something to happen). In my case the remote database server had a hiccup, and without pg_check_connection the listeners failed to notice, so never saw later notifications.

官方地址:https://www.php.net/manual/en/function.pg-get-notify.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3