您的位置:首页 > 产品设计 > UI/UE

Windows Azure: Service Bus Queues 入门

2013-01-21 23:05 519 查看
[code] <appSettings>

<!-- Service Bus specific app setings for messaging connections -->

<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[yourdomain].servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=[yourkey]" />

</appSettings>

[/code]
[/code]
在进行Queue操作时,将自动根据这个配置连接位于云端的Service Bus,当然我们也可以在运行时通过代码设定配置。

创建Service Bus Queue

[code]
[code] string queueName = "MyQueue";

NamespaceManager namespaceClient = NamespaceManager.Create();

QueueDescription myQueue = null;

if (!namespaceClient.QueueExists(queueName))

{

myQueue = namespaceClient.CreateQueue(queueName);

}

else

{

myQueue = namespaceClient.GetQueue(queueName);

}

[/code]
[/code]
发送消息

首先创建QueueClient对象

[code]
[code]MessagingFactory factory = MessagingFactory.Create();

QueueClient myQueueClient = factory.CreateQueueClient("MyQueue");

[/code]
[/code]
然后创建消息对象BrokeredMessage,在消息传输中,所有消息内容都需要封装成BrokeredMessage对象

[code]
[code] BrokeredMessage message = new BrokeredMessage();

message.Label = "SalesReport";

message.Properties.Add("Name", "Steven");

message.Properties.Add("Email", "Steven@hotmail.com");

message.Properties.Add("ProductCode", "P476534");

message.Properties.Add("Count", 1);

[/code]
[/code]
最后发送消息

[code]
[code] myQueueClient.Send(message);

[/code]
[/code]
接收消息

首先创建QueueClient对象

[code]
[code] string queueName = "MyQueue";

MessagingFactory factory = MessagingFactory.Create();

QueueClient myQueueClient = factory.CreateQueueClient(queueName, ReceiveMode.PeekLock);

[/code]
[/code]
我们注意到在创建客户端时,使用了一个参数:ReceiveMode,这个参数决定了消息的接收方式,ReceiveMode枚举定义如下:

[code]
[code] public enum ReceiveMode

{

PeekLock,

ReceiveAndDelete

}

[/code]
[/code]
ReceiveAndDelete,顾名思义,当客户端接收完消息以后,该消息即从队列中移除,其他客户端无法获取该消息。在这种模式下,消息最多被处理一次,但是处理过程中可能出现异常导致处理失败,所以这种模式适合应用可以容忍消息处理失败的情景中。

PeerLock,当客户端接收消息以后,并不移除,而是给消息上锁,此时其他客户端无法获取该消息。锁的过期时间默认为1分钟,可以自定义设置,最大可以设置为5分钟。如果处理成功,可以将消息从队列中移除(Complete),如果失败,可以将锁移除(Abandon),使得消息可以被其他客户端接收并处理。当应用无法容忍消息处理失败时,使用这种模式更为安全。

如果在创建客户端时没有定义ReceiveMode参数,则消息被接收以后不作任何操作,既不删除也不加锁,其他客户端仍然可以获取该消息。

接收消息

[code]
[code] BrokeredMessage message = myQueueClient.Receive();

if (message != null)

{

try

 {

ProcessMessage(message);


 message.Complete();

}

 catch

 {

 message.Abandon();

}

}

[/code]
[/code]
在具体例子中使用了两个Winform客户端程序来分别模拟发送方和接收方,点击 这里 下载源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: