### Create ServiceBusMessage with Custom Properties Source: https://context7.com/minghuaw/azservicebus/llms.txt Illustrates how to create and configure ServiceBusMessage objects with custom properties such as message ID, correlation ID, session ID, time-to-live, and application-specific metadata. This example focuses on setting various message identification and routing properties. ```rust use azservicebus::ServiceBusMessage; use std::time::Duration; fn main() -> Result<(), Box> { // Create message from string let mut message = ServiceBusMessage::new("Hello World"); // Set message identification message.set_message_id("msg-001")?; message.set_correlation_id("request-123"); // Set routing properties message.set_subject("order.created"); message.set_to("orders-queue"); message.set_reply_to("responses-queue"); message.set_content_type("application/json"); // Set session (for session-enabled queues) message.set_session_id(Some("session-abc".to_string()))?; message.set_reply_to_session_id(Some("reply-session".to_string()))?; // Set partition key (for partitioned entities) // Note: partition_key must match session_id if both are set // message.set_partition_key(Some("partition-1".to_string()))?; // Set time-to-live message.set_time_to_live(Duration::from_secs(3600))?; // Access message body println!("Body: {:?}", std::str::from_utf8(message.body())?); // Modify body message.set_body("Updated message content"); // Application properties for custom metadata if let Some(props) = message.application_properties_mut() { // Add custom properties } // Get properties println!("Message ID: {:?}", message.message_id()); println!("Subject: {:?}", message.subject()); println!("TTL: {:?}", message.time_to_live()); Ok(()) } ``` -------------------------------- ### Host build output with Python HTTP server Source: https://github.com/minghuaw/azservicebus/blob/main/examples/wasm32_in_browser/README.md Serve the contents of the `pkg` directory using Python's built-in HTTP server to make it accessible via a web browser. ```sh python -m http.server ``` -------------------------------- ### Send messages to queue Source: https://github.com/minghuaw/azservicebus/blob/main/README.md Demonstrates how to initialize a ServiceBusClient, create a sender, and send a batch of messages to a specified queue. ```rust use azservicebus::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Replace "" with your connection string, // which can be found in the Azure portal and should look like // "Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=;SharedAccessKey=" let mut client = ServiceBusClient::new_from_connection_string( "", ServiceBusClientOptions::default() ) .await?; // Replace "" with the name of your queue let mut sender = client.create_sender( "", ServiceBusSenderOptions::default() ) .await?; // Create a batch let mut message_batch = sender.create_message_batch(Default::default())?; for i in 0..3 { // Create a message let message = ServiceBusMessage::new(format!("Message {}", i)); // Try to add the message to the batch if let Err(e) = message_batch.try_add_message(message) { // If the batch is full, an error will be returned println!("Failed to add message {} to batch: {:?}", i, e); break; } } // Send the batch of messages to the queue match sender.send_message_batch(message_batch).await { Ok(()) => println!("Batch sent successfully"), Err(e) => println!("Failed to send batch: {:?}", e), } sender.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Receive messages from queue Source: https://github.com/minghuaw/azservicebus/blob/main/README.md Demonstrates how to initialize a ServiceBusClient, create a receiver, and complete messages after receiving them from a queue. ```rust use azservicebus::prelude::*; #[tokio::main] async fn main() -> Result<(), Box> { // Replace "" with your connection string, // which can be found in the Azure portal and should look like // "Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=;SharedAccessKey=" let mut client = ServiceBusClient::new_from_connection_string( "", ServiceBusClientOptions::default() ) .await?; // Replace "" with the name of your queue let mut receiver = client.create_receiver_for_queue( "", ServiceBusReceiverOptions::default() ) .await?; // Receive messages from the queue // This will wait indefinitely until at least one message is received let messages = receiver.receive_messages(3).await?; for message in &messages { let body = message.body()?; println!("Received message: {:?}", std::str::from_utf8(body)?); // Complete the message so that it is removed from the queue receiver.complete_message(message).await?; } receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Build for wasm32 with wasm-pack Source: https://github.com/minghuaw/azservicebus/blob/main/examples/wasm32_in_browser/README.md Use this command to build your Rust project for the `wasm32-unknown-unknown` target, preparing it for web deployment. ```sh wasm-pack build --target web ``` -------------------------------- ### Create ServiceBusClient with Connection String Source: https://context7.com/minghuaw/azservicebus/llms.txt Establishes an AMQP connection to Azure Service Bus using a connection string. Ensure the SERVICE_BUS_CONNECTION_STRING environment variable is set. The client should be disposed of when no longer needed. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions}; #[tokio::main] async fn main() -> Result<(), Box> { // Connection string format: // "Endpoint=sb://.servicebus.windows.net/;SharedAccessKeyName=;SharedAccessKey=" let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; // Create client with default options let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; println!("Connected to: {}", client.fully_qualified_namespace()); println!("Client identifier: {}", client.identifier()); println!("Is closed: {}", client.is_closed()); // Always dispose the client when done to close the AMQP connection client.dispose().await?; Ok(()) } ``` -------------------------------- ### Manage Subscription Rules with azservicebus Source: https://context7.com/minghuaw/azservicebus/llms.txt Demonstrates how to manage subscription rules for filtering messages in Azure Service Bus using SQL filters, correlation filters, and rule actions. Ensure the SERVICE_BUS_CONNECTION_STRING, SERVICE_BUS_TOPIC, and SERVICE_BUS_SUBSCRIPTION environment variables are set. ```rust use azservicebus::administration::{ CorrelationRuleFilter, FalseRuleFilter, SqlRuleAction, SqlRuleFilter, TrueRuleFilter, }; use azservicebus::ServiceBusClient; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let topic_name = std::env::var("SERVICE_BUS_TOPIC")?; let subscription_name = std::env::var("SERVICE_BUS_SUBSCRIPTION")?; let mut client = ServiceBusClient::new_from_connection_string(connection_string, Default::default()).await?; let mut rule_manager = client .create_rule_manager(&topic_name, &subscription_name) .await?; // List existing rules let rules = rule_manager.get_rules().await?; println!("Existing rules: {:?}", rules.len()); // Remove all existing rules for rule in rules { rule_manager.delete_rule(&rule.name).await?; } // Add correlation filter (matches message properties) let correlation_filter = CorrelationRuleFilter::builder() .subject("important") .content_type("application/json") .build(); rule_manager .create_rule("priority-filter", correlation_filter) .await?; // Add SQL filter with action let filter = SqlRuleFilter::new("user.region = 'us-east' AND priority > 5"); let action = SqlRuleAction::new("SET sys.Label = 'high-priority'"); rule_manager .create_rule("region-priority-filter", (filter, action)) .await?; // Add true filter (matches all messages) rule_manager .create_rule("match-all", TrueRuleFilter::new()) .await?; // Add false filter (matches no messages) rule_manager .create_rule("match-none", FalseRuleFilter::new()) .await?; rule_manager.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Peek Messages in Azservicebus (Rust) Source: https://context7.com/minghuaw/azservicebus/llms.txt Shows how to peek at messages without acquiring a lock or changing their state. Supports peeking the next message, from a specific sequence number, or multiple messages. Requires a ServiceBusClient and Receiver. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut receiver = client .create_receiver_for_queue(&queue_name, Default::default()) .await?; // Peek next message (from current position) let peeked = receiver.peek_message(None).await?; if let Some(msg) = peeked { let body = std::str::from_utf8(msg.body()?)?; let state = msg.state(); println!("Peeked message: {} (state: {:?})", body, state); } // Peek from specific sequence number let peeked = receiver.peek_message(Some(1)).await?; if let Some(msg) = peeked { println!("Sequence number: {}", msg.sequence_number()); } // Peek multiple messages let messages = receiver.peek_messages(10, None).await?; for msg in messages { println!("Peeked: {:?}", std::str::from_utf8(msg.body()?)?); } receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Receive Messages from Topic Subscriptions Source: https://context7.com/minghuaw/azservicebus/llms.txt Implement pub/sub messaging by creating receivers for topic subscriptions. Messages published to a topic are delivered to all subscriptions. Ensure messages are completed after processing to prevent redelivery. ```rust use azservicebus::{ ServiceBusClient, ServiceBusClientOptions, ServiceBusReceiverOptions, ServiceBusSenderOptions, }; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let topic_name = std::env::var("SERVICE_BUS_TOPIC")?; let subscription_name = std::env::var("SERVICE_BUS_SUBSCRIPTION")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; // Send to topic let mut sender = client .create_sender(&topic_name, ServiceBusSenderOptions::default()) .await?; sender.send_message("Hello from topic").await?; // Receive from subscription let mut receiver = client .create_receiver_for_subscription( &topic_name, &subscription_name, ServiceBusReceiverOptions::default(), ) .await?; let message = receiver.receive_message().await?; let body = std::str::from_utf8(message.body()?)?; println!("Received from subscription: {}", body); receiver.complete_message(&message).await?; sender.dispose().await?; receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Settle Messages in Azservicebus (Rust) Source: https://context7.com/minghuaw/azservicebus/llms.txt Demonstrates completing, abandoning, deferring, and dead-lettering messages. Requires setting up a ServiceBusClient and Receiver. Deferred messages must be retrieved by their sequence number. ```rust use azservicebus::{ ServiceBusClient, ServiceBusClientOptions, ServiceBusReceiverOptions, SubQueue, }; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut receiver = client .create_receiver_for_queue(&queue_name, Default::default()) .await?; // Complete - removes message from queue let message = receiver.receive_message().await?; receiver.complete_message(&message).await?; // Abandon - releases lock, message becomes available again let message = receiver.receive_message().await?; receiver.abandon_message(&message, None).await?; // Defer - message must be retrieved by sequence number later let message = receiver.receive_message().await?; let sequence_number = message.sequence_number(); receiver.defer_message(&message, None).await?; // Retrieve deferred message let deferred = receiver.receive_deferred_message(sequence_number).await?; if let Some(msg) = deferred { receiver.complete_message(&msg).await?; } // Dead-letter - moves message to dead-letter queue let message = receiver.receive_message().await?; receiver .dead_letter_message(&message, Default::default()) .await?; receiver.dispose().await?; // Receive from dead-letter queue let dlq_options = ServiceBusReceiverOptions { sub_queue: SubQueue::DeadLetter, ..Default::default() }; let mut dlq_receiver = client .create_receiver_for_queue(&queue_name, dlq_options) .await?; let dlq_message = dlq_receiver .receive_message_with_max_wait_time(std::time::Duration::from_secs(5)) .await?; if let Some(msg) = dlq_message { dlq_receiver.complete_message(&msg).await?; } dlq_receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Send and Receive Session Messages in Rust Source: https://context7.com/minghuaw/azservicebus/llms.txt Use this snippet to send messages with a specific session ID and then receive them in FIFO order. Ensure the queue has sessions enabled. Manages session state and locks. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions, ServiceBusMessage}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; // Queue must have sessions enabled let queue_name = std::env::var("SERVICE_BUS_SESSION_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; // Send session messages let mut sender = client .create_sender(&queue_name, Default::default()) .await?; let session_id = "order-12345"; for i in 1..=3 { let mut message = ServiceBusMessage::new(format!("Order step {}", i)); message.set_session_id(String::from(session_id))?; sender.send_message(message).await?; } sender.dispose().await?; // Accept specific session let mut receiver = client .accept_session_for_queue(&queue_name, session_id, Default::default()) .await?; println!("Session ID: {}", receiver.session_id()); println!("Session locked until: {:?}", receiver.session_locked_until()); // Receive session messages (FIFO order guaranteed) let messages = receiver.receive_messages(3).await?; for message in &messages { let body = std::str::from_utf8(message.body()?)?; println!("Received: {}", body); receiver.complete_message(message).await?; } // Session state management receiver.set_session_state(b"processing".to_vec()).await?; let state = receiver.session_state().await?; println!("Session state: {:?}", String::from_utf8(state)?); // Renew session lock receiver.renew_session_lock().await?; receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Accept Next Available Session in Rust Source: https://context7.com/minghuaw/azservicebus/llms.txt This snippet demonstrates how to accept the next available session with active messages without specifying a session ID. It's useful for dynamic session processing. Handles cases where no sessions are available. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_SESSION_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; // Accept next available session (will timeout if no sessions available) match client .accept_next_session_for_queue(&queue_name, Default::default()) .await { Ok(mut receiver) => { println!("Accepted session: {}", receiver.session_id()); let messages = receiver.receive_messages(10).await?; for message in &messages { receiver.complete_message(message).await?; } receiver.dispose().await?; } Err(e) => { println!("No sessions available or timeout: {:?}", e); } } client.dispose().await?; Ok(()) } ``` -------------------------------- ### Create ServiceBusClient with Azure Identity Source: https://context7.com/minghuaw/azservicebus/llms.txt Authenticates with Azure Service Bus using Azure Identity, supporting passwordless authentication via DefaultAzureCredential. Ensure the SERVICE_BUS_NAMESPACE and SERVICE_BUS_QUEUE environment variables are set. The client and sender should be disposed of when done. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions, ServiceBusSenderOptions}; use azure_identity::DefaultAzureCredential; #[tokio::main] async fn main() -> Result<(), Box> { // Namespace format: ".servicebus.windows.net" let namespace = std::env::var("SERVICE_BUS_NAMESPACE")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let credential = DefaultAzureCredential::new()?; let mut client = ServiceBusClient::new_from_token_credential( namespace, credential, ServiceBusClientOptions::default(), ) .await?; let sender = client .create_sender(queue_name, ServiceBusSenderOptions::default()) .await?; sender.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Send Messages in Batches with ServiceBusMessageBatch Source: https://context7.com/minghuaw/azservicebus/llms.txt Use `ServiceBusMessageBatch` to send multiple messages efficiently, ensuring they fit within Service Bus size limits. The batch prevents adding messages that would exceed the maximum allowable size. ```rust use azservicebus::{ CreateMessageBatchOptions, ServiceBusClient, ServiceBusClientOptions, ServiceBusMessage, }; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut sender = client .create_sender(&queue_name, Default::default()) .await?; // Create a message batch with default options let mut batch = sender.create_message_batch(CreateMessageBatchOptions::default())?; // Add messages to the batch - multiple ways to add batch.try_add_message("Message 1")?; batch.try_add_message(ServiceBusMessage::new("Message 2"))?; batch.try_add_message(ServiceBusMessage::from("Message 3"))?; // Add messages until batch is full for i in 4..100 { let message = ServiceBusMessage::new(format!("Message {}", i)); if let Err(e) = batch.try_add_message(message) { println!("Batch full at message {}: {:?}", i, e); break; } } // Send the entire batch sender.send_message_batch(batch).await?; sender.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Send Messages using ServiceBusSender Source: https://context7.com/minghuaw/azservicebus/llms.txt Sends messages to Azure Service Bus queues or topics using a ServiceBusSender. Supports sending single string messages, messages with properties, and multiple messages. Ensure the SERVICE_BUS_CONNECTION_STRING and SERVICE_BUS_QUEUE environment variables are set. The sender and client should be disposed of when finished. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions, ServiceBusMessage}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut sender = client .create_sender(&queue_name, Default::default()) .await?; // Send a simple string message sender.send_message("Hello World").await?; // Send a message with properties let mut message = ServiceBusMessage::new("Message with properties"); message.set_message_id("unique-id-123")?; message.set_subject("important"); message.set_content_type("text/plain"); message.set_correlation_id("correlation-456"); sender.send_message(message).await?; // Send multiple messages at once let messages = vec!["Message 1", "Message 2", "Message 3"]; sender.send_messages(messages).await?; println!("Entity path: {}", sender.entity_path()); println!("Sender identifier: {}", sender.identifier()); sender.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Receive Messages from Queues with ServiceBusReceiver Source: https://context7.com/minghuaw/azservicebus/llms.txt Use `ServiceBusReceiver` to receive and settle messages from queues. It supports PeekLock (default) and ReceiveAndDelete modes, with options for prefetching to improve throughput. Ensure you complete messages after processing to avoid redelivery. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions, ServiceBusReceiverOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut receiver = client .create_receiver_for_queue(&queue_name, ServiceBusReceiverOptions::default()) .await?; // Receive a single message (waits indefinitely) let message = receiver.receive_message().await?; let body = std::str::from_utf8(message.body()?)?; println!("Received: {}", body); receiver.complete_message(&message).await?; // Receive multiple messages let messages = receiver.receive_messages(10).await?; for message in &messages { let body = std::str::from_utf8(message.body()?)?; println!("Received: {}", body); receiver.complete_message(message).await?; } // Receive with timeout let message = receiver .receive_message_with_max_wait_time(std::time::Duration::from_secs(30)) .await?; if let Some(msg) = message { receiver.complete_message(&msg).await?; } receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Schedule Messages in AzServiceBus Rust Source: https://context7.com/minghuaw/azservicebus/llms.txt Schedules messages to be delivered at a future time. Supports setting the scheduled enqueue time directly on the message or using a dedicated schedule_message method. Scheduled messages can be cancelled before their enqueue time. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions, ServiceBusMessage}; use time::OffsetDateTime; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut sender = client .create_sender(&queue_name, Default::default()) .await?; // Method 1: Set scheduled enqueue time on message let mut message = ServiceBusMessage::new("Scheduled message 1"); let enqueue_time = OffsetDateTime::now_utc() + time::Duration::minutes(5); message.set_scheduled_enqueue_time(enqueue_time); sender.send_message(message).await?; // Method 2: Use schedule_message method (returns sequence number) let enqueue_time = OffsetDateTime::now_utc() + time::Duration::minutes(10); let sequence_number = sender .schedule_message("Scheduled message 2", enqueue_time) .await?; println!("Scheduled message sequence number: {}", sequence_number); // Cancel a scheduled message sender.cancel_scheduled_message(sequence_number).await?; println!("Cancelled scheduled message"); // Schedule multiple messages let messages = vec!["Batch 1", "Batch 2", "Batch 3"]; let enqueue_time = OffsetDateTime::now_utc() + time::Duration::minutes(15); let sequence_numbers = sender.schedule_messages(messages, enqueue_time).await?; println!("Scheduled {} messages", sequence_numbers.len()); // Cancel multiple scheduled messages sender.cancel_scheduled_messages(sequence_numbers).await?; sender.dispose().await?; client.dispose().await?; Ok(()) } ``` -------------------------------- ### Renew Message Lock in AzServiceBus Rust Source: https://context7.com/minghuaw/azservicebus/llms.txt Renews message locks for long-running processing to prevent messages from becoming available to other receivers prematurely. Requires a mutable reference to the message to update its locked_until timestamp. ```rust use azservicebus::{ServiceBusClient, ServiceBusClientOptions}; #[tokio::main] async fn main() -> Result<(), Box> { let connection_string = std::env::var("SERVICE_BUS_CONNECTION_STRING")?; let queue_name = std::env::var("SERVICE_BUS_QUEUE")?; let mut client = ServiceBusClient::new_from_connection_string( connection_string, ServiceBusClientOptions::default(), ) .await?; let mut receiver = client .create_receiver_for_queue(&queue_name, Default::default()) .await?; let message = receiver .receive_message_with_max_wait_time(std::time::Duration::from_secs(30)) .await?; if let Some(mut message) = message { println!("Locked until: {:?}", message.locked_until()); // Simulate long processing tokio::time::sleep(std::time::Duration::from_secs(10)).await; // Renew the lock (mutable reference needed as locked_until is updated) receiver.renew_message_lock(&mut message).await?; println!("Lock renewed until: {:?}", message.locked_until()); // Complete processing receiver.complete_message(&message).await?; } receiver.dispose().await?; client.dispose().await?; Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.