rust中使用rabbitMQ


文中使用amiquip這個包來使用rabbitmq 我相當於就是把那個英文文檔看了一遍 但是還沒看全 因為rust得線程這個東西我還沒學到(別的語言的線程也是學的不是很精通)
首先放上官方文檔的地址https://docs.rs/amiquip/latest/amiquip/
如果有不全的大家可以看文檔
首先第一步 在cargo.toml中引入依賴

點擊查看代碼 ``` [dependencies] amiquip = { version = "0.4", default-features = false } ```

接下來是慣例得hello world 例子
首先是發布者

點擊查看代碼
use amiquip::{Connection, Exchange, Publish, Result};

fn main() -> Result<()> {
    // Open connection.
    let mut connection = Connection::insecure_open("amqp://guest:guest@localhost:5672")?;

    // Open a channel - None says let the library choose the channel ID.
    let channel = connection.open_channel(None)?;

    // Get a handle to the direct exchange on our channel.
    let exchange = Exchange::direct(&channel);

    // Publish a message to the "hello" queue.
    exchange.publish(Publish::new("hello there".as_bytes(), "hello"))?;

    connection.close()
}

然后是消費者

點擊查看代碼
// Port of https://www.rabbitmq.com/tutorials/tutorial-one-python.html. Run this
// in one shell, and run the hello_world_publish example in another.
use amiquip::{Connection, ConsumerMessage, ConsumerOptions, QueueDeclareOptions, Result};

fn main() -> Result<()> {
    // Open connection.
    let mut connection = Connection::insecure_open("amqp://guest:guest@localhost:5672")?;

    // Open a channel - None says let the library choose the channel ID.
    let channel = connection.open_channel(None)?;

    // Declare the "hello" queue.
    let queue = channel.queue_declare("hello", QueueDeclareOptions::default())?;

    // Start a consumer.
    let consumer = queue.consume(ConsumerOptions::default())?;
    println!("Waiting for messages. Press Ctrl-C to exit.");

    for (i, message) in consumer.receiver().iter().enumerate() {
        match message {
            ConsumerMessage::Delivery(delivery) => {
                let body = String::from_utf8_lossy(&delivery.body);
                println!("({:>3}) Received [{}]", i, body);
                consumer.ack(delivery)?;
            }
            other => {
                println!("Consumer ended: {:?}", other);
                break;
            }
        }
    }

    connection.close()
}

我在學習時 那個消費者得報錯 原因是 durable 我的服務器上部署的true 但是他默認配置是false

於是就實例化了一個這個配置結構體
在實例化得時候 又學到了這個rabbitmq得一些參數怎么設置和這個BTreeMap
這個BTreeMap需要引入std::collections::BTreeMap;

點擊查看代碼
   let declartOption = QueueDeclareOptions {
        durable:true,
        exclusive: false,
        auto_delete: false,
        arguments:BTreeMap::new(),
    };

然后就可以完成簡單的發布者和消費者了

之后再完善再寫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM