我有一个在 windows azure 中运行的辅助角色,它会生成消息。我有一个 ASP.NET MVC 应用程序,它有一个 SignalR 中心。我想将消息从辅助角色推送到 SignalR 中心,然后将这些消息实时推送到连接的客户端。我的想法是使用 ASP.NET MVC 应用程序将从中读取的 Azure 服务总线队列。这一切似乎都是一个非常简单的概念,但我不确定如何在 MVC 应用程序中连接服务总线 QueueClient。我可以找到大量使用 ASP.NET MVC 将消息放入队列中以供辅助角色服务拾取的示例,但反之则不然。
问题:有办法做到这一点吗?有人能给我指出一些样本等的方向吗?
最佳答案
在我们的项目中,我们在 MvcApplication > Application_Start 上使用它:
new Thread(t => Container.Resolve<IMessageRouter>().StartRouting()).Start();
我们也使用DI(Windsor容器),路由器注册为Transient。路由器以并行线程中的 Web 应用程序启动并始终工作。
路由器具有 SignalR 集线器连接上下文和主题监听器(主题客户端包装器):
public class MessageRouter : IMessageRouter
{
private string _subscriptionName = "Subscription_0";
private IHubConnectionContext ClientContext
{
get { return GlobalHost.ConnectionManager.GetHubContext<MessageHub>().Clients; }
}
private RoleInstance CurrentRoleInstance
{
get // try to get current Azure role instance
{
if (RoleEnvironment.IsAvailable && RoleEnvironment.CurrentRoleInstance != null)
{
return Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.CurrentRoleInstance;
}
return null; // return null if not Azure environment
}
}
private string TopicName
{
get { return ConfigurationHelper.TopicName; }
}
private string TopicConnectionString
{
get { return ConfigurationHelper.TopicConnectionString; }
}
public ITopicListener TopicListener { get; set; }
public void OnMessage(QueueMessage message)
{
ClientContext.Group(message.GetRecipientGroup()).updateProgress(message.GetBody<string>());
}
public void StartRouting()
{
TopicListener.Bind(TopicConnectionString, TopicName, _subscriptionName).StartListening(OnMessage);
}
public MessageRouter()
{
if (CurrentRoleInstance != null) // check Azure environment is exist
{
int instanceIndex = 0; string instanceId = CurrentRoleInstance.Id;
if (!int.TryParse(instanceId.Substring(instanceId.LastIndexOf(".") + 1), out instanceIndex)) // on cloud
{
int.TryParse(instanceId.Substring(instanceId.LastIndexOf("_") + 1), out instanceIndex); // on compute emulator
}
_subscriptionName = String.Format("{0}_{1}", CurrentRoleInstance.Role.Name, instanceIndex);
}
}
}
而且它有效。希望这会有所帮助。
关于asp.net-mvc - 如何让 ASP.NET MVC 应用程序从 Azure 服务总线队列读取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21103025/