我正在从网络角色向工作人员角色发送消息。早些时候这些消息被正确地立即收到,但现在无处可见一些消息,即使所有消息的内容相同。就像我现在发送一条消息一样,它没有收到但是在那之后如果我发送另一条消息则接收到最新消息。之前没有收到的那个,几秒钟后突然收到,或者因为生存时间已经过期而有时会收到死信。
我无法弄清楚问题是什么,有什么想法吗?或者这种行为在服务总线上是否正常?
这是以工作者角色接收消息的方式
编辑:
public override void Run()
{
while (!IsStopped)
{
try
{
if (BroadcastReceived)
{
BroadcastReceived = false;
// Receive the message from Web Role to upload the broadcast to queue
BroadcastClient.BeginReceive(OnWebRoleMessageReceived, null);
}
if (SignalRMessageReceived)
{
SignalRMessageReceived = false;
// Receive the message from SignalR BroadcastHub
SignalRClient.BeginReceive(OnSignalRMessageReceived, null);
}
if (SignalRFirstTimeMessageReceived)
{
SignalRFirstTimeMessageReceived = false;
// Receive the message from SignalR BroadcastHub
SignalRFirstTimeClient.BeginReceive(OnSignalRFirstTimeMessageReceived, null);
}
}
}
public void OnWebRoleMessageReceived(IAsyncResult iar)
{
BrokeredMessage receivedBroadcastMessage = null;
receivedBroadcastMessage = BroadcastClient.EndReceive(iar);
if (receivedBroadcastMessage != null)
{
// Process the message
receivedBroadcastMessage.Complete();
}
BroadcastReceived = true;
}
更新:
BroadcastClient = CloudStorageHelper.GetServiceBusQueueClient(Queuenames.ApiToWorkerRole);
public static QueueClient GetServiceBusQueueClient(string queuename)
{
string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.QueueExists(queuename))
{
namespaceManager.CreateQueue(queuename);
}
QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, queuename);
return Client;
}
网络角色:
var queueClient = CloudStorageHelper.GetServiceBusQueueClient(Queuenames.ApiToWorkerRole);
//for testing purposes
record.Username = "owner";
record.Channel = "World";
record.Title = "Sample";
record.Duration = 10;
BrokeredMessage message = new BrokeredMessage(record);
queueClient.Send(message);
答案 0 :(得分:1)
问题出现了,因为在我们的工作角色中,我们不断检查服务总线队列以查看消息是否已到达。当我们启动本地和云工作者角色时,两个工作者角色都会尝试从同一个服务总线队列接收新消息。因此有时云端接受它,有时接受本地接收它。
为云和本地项目使用不同的服务总线队列名称解决了这个问题。
答案 1 :(得分:0)
在上面的worker角色中,您只在Run中执行一次代码。所以基本上这表明每次运行辅助角色时都会处理一条消息?处理循环中消息的典型代码如下所示:
public override void Run()
{
while (!IsStopped)
{
try
{
// Receive the message
BrokeredMessage receivedMessage = null;
receivedMessage = Client.Receive();
if (receivedMessage != null)
{
// Process the message
receivedMessage.Complete(); // Unless you do this the message goes back in the Queue
}
}
catch (MessagingException e)
{
if (!e.IsTransient)
{
Trace.WriteLine(e.Message);
throw;
}
Thread.Sleep(10000); // optional if you want to add a delay
}
}
}