如何将相同的消息发送到多个客户端

时间:2013-09-25 20:19:44

标签: azure azureservicebus

我刚刚开始玩天蓝色和服务总线。我试图能够向多个客户端发送相同的消息。在其他消息传递解决方案中,如果您有多个客户端正在侦听主题并且您向主题发送消息,则他们都会收到消息。使用Azure,只有其中一个订阅者获取消息。我相信我错过了任何人都可以提供指针的东西?我的示例代码如下。

string connectionString =
"Endpoint=sb://xxx.servicebus.windows.net/;SharedSecretIssuer=owner;SharedSecretValue=xxxxxxxxxxxxxxxxxxxxxxxxxxxx=";
NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
string topic = TestTopic.Replace("/", ".").Replace("{", "-").Replace("}", "-");
if (!namespaceManager.TopicExists(topic))
{
var td = new TopicDescription(topic)
    {
    MaxSizeInMegabytes = 5120,
    DefaultMessageTimeToLive = new TimeSpan(0, 1, 0),
    };

namespaceManager.CreateTopic(td);
}


var message = new {CurrencyCode = "AUD", EffectiveDate = DateTime.Today, Rate = .97M};

TopicClient publisher = TopicClient.CreateFromConnectionString(connectionString, topic);
var bm = new BrokeredMessage("fff");
bm.Properties["Topic"] = ".xxx.fxrates.aud";

int messagesReceived = 0;
int messagesReceived2 = 0;

if (namespaceManager.SubscriptionExists(topic, "test") == false)
{
SubscriptionDescription sub = namespaceManager.CreateSubscription(topic, "test");
}

SubscriptionClient subscriber = SubscriptionClient.CreateFromConnectionString(connectionString, topic,
                                      "test",
                                      ReceiveMode.ReceiveAndDelete);
SubscriptionClient subscriber2 = SubscriptionClient.CreateFromConnectionString(connectionString, topic,
                                       "test",
                                       ReceiveMode.ReceiveAndDelete);
subscriber.OnMessage(delegate { messagesReceived++; });

subscriber2.OnMessage(delegate { messagesReceived2++; });

publisher.Send(bm);
namespaceManager.DeleteTopic(topic);

1 个答案:

答案 0 :(得分:0)

首先,您必须为订阅者命名!目前,您的两个订阅者都被命名为“test”。其次,如果您希望其他订阅者也收到消息,您必须执行ReceiveMode.PeekLock,但不能使用ReceiveMode.ReceiveAndDelete。

我知道我们开发人员讨厌RTFM,但是当没有其他任何帮助时(包括StackOverflow问题),最好先看一下(手册):Service Bus Queues, Topics and Subscriptions是了解其工作原理的一个很好的资源。 How to use Service Bus Topics/Subscriptions将带您到正确的位置。