2014-01-13 4 views
3

메시지를 생성하는 windows azure에서 worker 역할을 실행하고 있습니다. SignalR 허브가있는 ASP.NET MVC 앱이 있습니다. 나는 worker 역할의 메시지를 SignalR 허브로 보내고 싶습니다. 그러면이 클라이언트가 실시간으로 연결된 클라이언트에게 Push합니다. 내 생각은 ASP.NET MVC 응용 프로그램에서 읽을 Azure 서비스 버스 큐를 사용하는 것입니다. 그것은 모두 개념의 직선적 인 것처럼 보이지만 MVC 응용 프로그램에서 서비스 버스 QueueClient를 연결하는 방법을 잘 모르겠습니다. ASP.NET MVC에서 작업자 역할 서비스에 의해 선택 될 대기열에 메시지를 넣지 만, 다른 방법으로는 사용할 수없는 샘플을 많이 찾을 수 있습니다.Azure 서비스 버스 대기열에서 읽을 ASP.NET MVC 앱을 얻으려면 어떻게해야합니까?

질문 : 방법이 있습니까? 누군가가 샘플 등의 방향으로 나를 가리킬 수 있을까? http://www.windowsazure.com/en-us/documentation/articles/service-bus-dotnet-how-to-use-queues/

에서 "큐에서 메시지를 수신하는 방법"하지만, 당신이 메시지를 생성하는 작업자 역할을하고 SignalR을 사용하려는 경우, 내가위한 방송 허브로 그 작업자 역할을 사용하는 것이 좋습니다 것

답변

1

를 참조하십시오. 병렬 스레드에서 웹 응용 프로그램으로 시작하고 항상 작동하는 라우터.

라우터는 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); 
     } 
    } 
} 

을 그리고 그것은 작동합니다. 희망이 도움이됩니다.

+0

내가 찾고 있던 것과 정확히 같은 종류의 - 많은 감사와 많은 감사. 이 같은 MVC 애플 리케이션 내에서 다른 스레드를 스핀 꽤 합법적입니까? 그리고 서버 브로드 캐스트 패턴을 살펴보면 @viperguynaz와 비슷한 클라이언트 컨텍스트를 얻게됩니다. 또한 Brady Gaster의 [post] (http://www.bradygaster.com/post/from-the-cloud-to-the-client) (아마도 대체되었지만)에서 sb 큐 클라이언트를 SignalR 허브에 주입하는 것에 관심이 있습니다 . 도와 줘서 고마워. – jcaddy

1

읽기 우리는 또한 DI (윈저 컨테이너)를 사용하는

new Thread(t => Container.Resolve<IMessageRouter>().StartRouting()).Start(); 

, 라우터가 일시적으로 등록되어 있습니다 : - SignalR 우리가 MvcApplication> 위해 Application_Start에서이를 사용하는 우리의 프로젝트에서 Tutorial: Server Broadcast with SignalR 2.0

+0

감사합니다. 아마 내 게시물에서 더 말했어야했다. 작업자 역할은 클라이언트에서 액세스 할 수 없으며 Azure 가상 네트워크에 있습니다. 그래서 메시지를 SignalR 허브에 보내야합니다. 이제는 서비스 버스 대기열 클라이언트를 생성 할 수 있지만 일시적인 허브 호출을 넘어서는 지속성이 필요합니다. 따라서 SignalR 허브를 호스팅하는 ASP.NET 사이트에서 <항상> 구성 요소를 실행해야합니다. AppStart - WebActivator에서 일부 대기열 클라이언트를 위로 돌리는 방법이있을 수 있습니까? - 그런 다음 DI를 사용하여 허브 클래스에 주입하십시오. 어떤 아이디어? – jcaddy

-1
//Fetch connection string from config 
     string connectionString = ConfigurationManager.AppSettings["connectionString"]; 
     // Create the connection 
     MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString); 
     //Provide the queue name in the service bus 
     MessageReceiver receiver = factory.CreateMessageReceiver("queue Name"); 
     BrokeredMessage retrievedMessage = receiver.Receive(); 
     if (retrievedMessage != null) 
     { 
      try 
      { 
       string output = retrievedMessage.GetBody<string>(); 
       //In the output string you will get the message from the queue. 
       retrievedMessage.Complete(); 
      } 
      catch (Exception ex) 
      { 
       retrievedMessage.Abandon(); 
      } 
     } 
+0

어떻게 작동하는지에 대한 설명이 도움이 될 것입니다. –

관련 문제