yoshidan / google-cloud-rust

Google Cloud Client Libraries for Rust.
MIT License
233 stars 85 forks source link

Need example using real project configuration #116

Closed bujosa closed 1 year ago

bujosa commented 1 year ago

Add example with real pubsub project config, this is the example in the documentation

use google_cloud_pubsub::client::{Client, ClientConfig}; use google_cloud_gax::cancel::CancellationToken; use google_cloud_googleapis::pubsub::v1::PubsubMessage; use google_cloud_pubsub::topic::TopicConfig; use google_cloud_pubsub::subscription::SubscriptionConfig; use google_cloud_gax::grpc::Status; use tokio::task::JoinHandle;

// Client config

[tokio::main]

async fn main() -> Result<(), Status> {

// Create pubsub client.
// `use google_cloud_default::WithAuthExt;` is required to use default authentication.
let config = ClientConfig::default();//.with_auth().await.unwrap();
let client = Client::new(config).await.unwrap();

// Create topic.
let topic = client.topic("test-topic");
if !topic.exists(None, None).await? {
    topic.create(None, None, None).await?;
}

// Start publisher.
let publisher = topic.new_publisher(None);

// Publish message.
let tasks : Vec<JoinHandle<Result<String,Status>>> = (0..10).into_iter().map(|_i| {
    let publisher = publisher.clone();
    tokio::spawn(async move {
        let mut msg = PubsubMessage::default();
        msg.data = "abc".into();
        // Set ordering_key if needed (https://cloud.google.com/pubsub/docs/ordering)
        // msg.ordering_key = "order".into();

        // Send a message. There are also `publish_bulk` and `publish_immediately` methods.
        let mut awaiter = publisher.publish(msg).await;

        // The get method blocks until a server-generated ID or an error is returned for the published message.
        awaiter.get(None).await
    })
}).collect();

// Wait for all publish task finish
for task in tasks {
    let message_id = task.await.unwrap()?;
}

// Wait for publishers in topic finish.
let mut publisher = publisher;
publisher.shutdown();

Ok(())

}