Skip to main content

only_a_publisher/
only_a_publisher.rs

1use std::time::Duration;
2use tokio::time::sleep;
3
4use resilient_rabbitmq_client::prelude::*;
5
6// First we declare our consumer type.
7#[derive(Clone)]
8pub struct MyRabbitMQClient;
9
10// We still have to implement this trait (for now).
11#[async_trait]
12impl AsyncConsumer for MyRabbitMQClient {
13    #[allow(unused_variables)]
14    async fn consume(
15        &mut self,
16        channel: &Channel,
17        deliver: Deliver,
18        basic_properties: BasicProperties,
19        content: Vec<u8>,
20    ) {
21        // Not doing anything. This will never be called.
22    }
23}
24
25#[tokio::main]
26async fn main() {
27    // Declare a RabbitMqClientHandler
28    let rabbitmq_connection_arguments =
29        ConnectionArguments::new("localhost", 5672, "guest", "guest");
30    let mut resilient_rabbitmq_client: RabbitMqClientHandler<MyRabbitMQClient> =
31        RabbitMqClientHandler::new(rabbitmq_connection_arguments).await;
32
33    // Declare a PublishChannel
34    let mut publisher = resilient_rabbitmq_client.create_publisher().await.unwrap();
35    // Get a channel from it. This channel is meant to be used to communicate with the PublishChannel type.
36    let publish_sender = resilient_rabbitmq_client
37        .get_publish_sender_clone()
38        .unwrap();
39
40    // For the example, we spawn a task which will publish some random data on an "incoming" routing key every second.
41    tokio::task::spawn(async move {
42        loop {
43            publish_sender
44                .send(DataToPublish::from(
45                    "amq.direct".to_string(),
46                    "incoming".to_string(),
47                    "random data".to_string(),
48                ))
49                .await
50                .unwrap();
51
52            sleep(Duration::from_secs(1)).await;
53        }
54    });
55
56    // Keep alive both the client and the publisher
57    tokio::join!(
58        publisher.keep_ready_to_publish(),
59        resilient_rabbitmq_client.keep_alive()
60    );
61}