首页 > 解决方案 > How do I use the postgres crate to receive table modification events from PostgreSQL?

问题描述

I have a Rust process dealing with a PostgreSQL database. This process communicates with a server process to pass on the details using MPSC channels. I am stuck on how to listen for and process events for table modification.

I tried using tokio-postgres but it seems there is an issue with it on Windows.

标签: postgresqlrust

解决方案


在 PostgreSQL 的特定频道上监听事件如下:-

// Establish connection with database.
let url = "postgresql://root:root1234@127.0.01/test";
let conn = Connection::connect(url, TlsMode::None).unwrap();

// Listen for events on channel 'myevent'.
conn.execute("LISTEN myevent", &[]).expect("Could not send LISTEN");
let notifications = conn.notifications();
let mut it = notifications.blocking_iter();

println!("Waiting for notifications...");
loop {
    let a = it.next();
    match a {
        Ok(Some(b)) => {
            println!("{:?}", b);
        },
        Err(e) => println!("Got error {:?}", e),
        _ => panic!("Unexpected operation!!!")
    }
}

推荐阅读