2011-12-09 3 views
1

저는 C#으로 ActiveMQ를 사용하는 초보자입니다. 하나의 버튼과 하나의 라벨로 간단한 윈도우 폼을 만들었습니다. 버튼을 클릭하면 큐에 메시지를 보내고 레이블은 방금 보낸 메시지로 초기화됩니다. 물론 직접 레이블을 초기화 할 수는 있지만 내 레이블을 업데이트하려면 큐에서 메시지를 소비하는 방식으로 양식을 작성해야합니다.방금 ​​ActiveMQ 및 C와 함께 보낸 메시지 처리

문제는 내가 라벨을 업데이트하기 위해 동일한 양식의 메시지를 처리하지 못한다는 것입니다. 내 소비자 코드는 전혀 호출되지 않았지만 내 양식의 Load 이벤트에서 초기화됩니다. 내 창문 양식을 닫고 다시 시작한 다음 내 레이블도 업데이트되어 있지만 내가 그것을 닫고 다시 열하지 않으려면 여기에 코드를

protected override void OnLoad(EventArgs e) 
    { 
     base.OnLoad(e); 
     InitializeHandlerAMQ(); 
    } 

    private void InitializeHandlerAMQ() 
    { 
     Tchat tchat = null; 
     IDestination dest = _session.GetQueue(QUEUE_DESTINATION); 
     using(IMessageConsumer consumer = _session.CreateConsumer(dest)) 
     { 
      IMessage message; 
      while((message = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) 
      { 
       var objectMessage = message as IObjectMessage; 
       if(objectMessage != null) 
       { 
        tchat = objectMessage.Body as Tchat; 
        if (tchat != null) 
        { 
         textBox2.Text += string.Format("{0}{1}", tchat.Message, Environment.NewLine); 
        } 
       } 
      } 
     } 
    } 

을합니다.

의견이 있으십니까?

답변

5

다음과 같은 이벤트 위임을 사용하여 클래스를 만들어보세요.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Apache.NMS; 
using Apache.NMS.ActiveMQ; 
using Apache.NMS.ActiveMQ.Commands; 

namespace Utilities 
{ 
    public delegate void QMessageReceivedDelegate(string message); 
    public class MyQueueSubscriber : IDisposable 
    { 
     private readonly string topicName = null; 
     private readonly IConnectionFactory connectionFactory; 
     private readonly IConnection connection; 
     private readonly ISession session; 
     private readonly IMessageConsumer consumer; 
     private bool isDisposed = false; 
     public event QMessageReceivedDelegate OnMessageReceived; 

     public MyQueueSubscriber(string queueName, string brokerUri, string clientId) 
     { 
      this.topicName = queueName; 
      this.connectionFactory = new ConnectionFactory(brokerUri); 
      this.connection = this.connectionFactory.CreateConnection(); 
      this.connection.ClientId = clientId; 
      this.connection.Start(); 
      this.session = connection.CreateSession(); 
      ActiveMQQueue topic = new ActiveMQQueue(queueName); 
      //this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false); 
      this.consumer = this.session.CreateConsumer(topic, "2 > 1"); 
      this.consumer.Listener += new MessageListener(OnMessage); 

     } 

     public void OnMessage(IMessage message) 
     { 
      ITextMessage textMessage = message as ITextMessage; 
      if (this.OnMessageReceived != null) 
      { 
       this.OnMessageReceived(textMessage.Text); 
      } 
     } 

     #region IDisposable Members 

     public void Dispose() 
     { 
      if (!this.isDisposed) 
      { 
       this.consumer.Dispose(); 
       this.session.Dispose(); 
       this.connection.Dispose(); 
       this.isDisposed = true; 
      } 
     } 

     #endregion 

    } 
} 

윈폼이 당신의 창에서

MyQueueSubscriber QueueSubscriber = new MyQueueSubscriber(QueueName, ActiveMQHost, QueueClientId); 
    QueueSubscriber.OnMessageReceived += new QMessageReceivedDelegate(QueueSubscriber_OnMessageReceived); 

static void QueueSubscriber_OnMessageReceived(string message) 
{ 
     SetText(message); 
} 

    private void SetText(string text) 
    { 
     // InvokeRequired required compares the thread ID of the 
     // calling thread to the thread ID of the creating thread. 
     // If these threads are different, it returns true. 
     if (this.textBox1.InvokeRequired) 
     { 
      SetTextCallback d = new SetTextCallback(SetText); 
      this.Invoke(d, new object[] { text }); 
     } 
     else 
     { 
      this.labelname.value = text; 
     } 
    } 

자원처럼 큐에 가입 형성 가입자 클래스 : 불행히도에 많은없는 자원이있다 C# & ActiveMQ를 가르쳐주세요. http://activemq.apache.org/nms/을 사용해보세요. 꽤 좋은 도구였습니다.

http://www.codersource.net/MicrosoftNet/CAdvanced/PublishSubscribeinCusingActiveMQ.aspx에서 작은 기사를 봅니다. 면책 조항 : 이것은 내 웹 사이트이며 기사는 저에게 썼습니다. 죄송합니다 자기 홍보. 하지만이 주제와 관련이 있다고 생각합니다.

+0

다른 리소스 : ".NET (샘플 채팅 응용 프로그램)의 ActiveMQ"https://code.msdn.microsoft.com/windowsapps/ActiveMQ-in-NET-Sample-9406441a –