从 .net 5 中的 Azure 服务总线队列获取消息 ID

Get message id from Azure Service Bus Queue in .net 5

我想向服务总线队列发送消息并接收它的 ID。

sdk 示例似乎提供了解决方案。

string connectionString = "<connection_string>";
string queueName = "<queue_name>";
// since ServiceBusClient implements IAsyncDisposable we create it with "await using"
await using var client = new ServiceBusClient(connectionString);

// create the sender
ServiceBusSender sender = client.CreateSender(queueName);

// create a message that we can send. UTF-8 encoding is used when providing a string.
ServiceBusMessage message = new ServiceBusMessage("Hello world!");

// send the message
await sender.SendMessageAsync(message);

// create a receiver that we can use to receive the message
ServiceBusReceiver receiver = client.CreateReceiver(queueName);

// the received message is a different type as it contains some service set properties
ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

string id = receivedMessage.Id

ReceiveMessageAsync() 将 return 队列中的第一项,因此我如何确保在发送消息之间另一条消息不会到达队列(来自另一客户端)

await sender.SendMessageAsync(message);

并收到它

await receiver.ReceiveMessageAsync();

您可以通过 MessageId 属性:

设置给定 ServiceBusMessage 的标识符

The message identifier is an application-defined value that uniquely identifies the message and its payload. The identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If enabled, the duplicate detection feature identifies and removes second and further submissions of messages with the same MessageId.

只需将标识符定义为 GUID 并保存该值。不需要额外的复杂性。

更多信息:

ServiceBusMessage.MessageId Property