程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成同Active MQ通信的辦法

C#完成同Active MQ通信的辦法

編輯:C#入門知識

C#完成同Active MQ通信的辦法。本站提示廣大學習愛好者:(C#完成同Active MQ通信的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成同Active MQ通信的辦法正文


本文實例講述了C#完成同Active MQ通信的辦法。分享給年夜家供年夜家參考,詳細以下:

內容概要:

重要以源碼的情勢引見若何用C#完成同Active MQ 的通信。本文假定你曾經准確裝置JDK1.6.x,懂得Active MQ並有必定的編程基本。

注釋:

JMS 法式的終究目標是臨盆和花費的新聞能被其他法式應用,JMS 的 Message 是一個既簡略又不乏靈巧性的根本格局,許可創立分歧平台上相符非JMS 法式格局的新聞。
Message 由新聞頭,屬性和新聞體三部分構成。
Active MQ支撐過濾機制,即臨盆者可以設置新聞的屬性(Properties),該屬性與花費者真個Selector對應,只要花費者設置的selector與新聞的Properties婚配,新聞才會發給該花費者。Topic和Queue都支撐Selector。

示例代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Apache.NMS;
using System.Diagnostics;
using Apache.NMS.Util;
using System.Windows.Threading;
/*
 * 功效描寫:C#應用ActiveMQ示例
 * 修正次數:2
 * 最初更新: by Kagula,2012-07-31
 *
 * 條件前提:
 * [1]apache-activemq-5.4.2
 * [2]Apache.NMS.ActiveMQ-1.5.6-bin
 * [3]WinXP SP3
 * [4]VS2008 SP1
 * [5]WPF工程 With .NET Framework 3.5
 *
 * 啟動
 *
 * 不帶平安掌握方法啟動
 * [你的解壓途徑]\apache-activemq-5.4.2\bin\activemq.bat
 *
 * 平安方法啟動
 * 添加情況變量:      ACTIVEMQ_ENCRYPTION_PASSWORD=activemq
 * [你的解壓途徑]\apache-activemq-5.4.2\bin>activemq xbean:file:../conf/activemq-security.xml
 *
 * Active MQ 治理地址
 * http://127.0.0.1:8161/admin/
 * 添加拜訪"http://127.0.0.1:8161/admin/"的限制
 *
 * 第一步:添加拜訪限制
 * 修正D:\apache\apache-activemq-5.4.2\conf\jetty.xml文件
 * 上面這行編碼,原
 * <property name="authenticate" value="true" />
 * 修正為
 * <property name="authenticate" value="false" />
 *
 * 第二步:修正登錄用戶名暗碼,缺省份別為admin,admin
 * D:\apache\apache-activemq-5.4.2\conf\jetty-realm.properties
 *
 * 用戶治理(條件:以平安方法啟動ActiveMQ)
 *
 * 在[你的解壓途徑]\apache-activemq-5.4.2\conf\credentials.properties文件中修正默許的用戶名暗碼
 * 在[你的解壓途徑]\apache-activemq-5.4.2\conf\activemq-security.xml文件中可以添加新的用戶名
 * e.g. 添加oa用戶,暗碼同用戶名。
 * <authenticationUser username="oa" password="oa" groups="users,admins"/>
 *
 * 在[你的解壓途徑]\apache-activemq-5.4.2\conf\activemq-security.xml文件中你還可以設置指定的Topic或Queue
 * 只能被哪些用戶組read 或 write。
 *
 *
 * 設置裝備擺設C# with WPF項目
 * 項目標[Application]->[TargetFramework]屬性設置為[.NETFramework 3.5](這是VS2008WPF工程的默許設置)
 * 添加[你的解壓途徑]\Apache.NMS.ActiveMQ-1.5.6-bin\lib\Apache.NMS\net-3.5\Apache.NMS.dll的援用
 * Apache.NMS.dll相當於接口
 *
 * 假如是以Debug方法調試
 * 把[你的解壓途徑]\Apache.NMS.ActiveMQ-1.5.6-bin\build\net-3.5\debug\目次下的
 * Apache.NMS.ActiveMQ.dll文件復制到你項目標Debug目次下
 * Apache.NMS.ActiveMQ.dll相當於完成
 *
 * 假如是以Release方法調試
 * 參考上文,去取Apache.NMS,Release目次下響應的DLL文件,並復制到你項目標Release目次下。
 *
 *
 * 參考材料
 * [1]《C#挪用ActiveMQ官方示例》 http://activemq.apache.org/nms/examples.html
 * [2]《ActiveMQ NMS下載地址》http://activemq.apache.org/nms/activemq-downloads.html
 * [3]《Active MQ在C#中的運用示例》http://www.jb51.net/article/87956.htm
 * [4]《NMS API Reference》http://activemq.apache.org/nms/nms-api.html
 */
namespace testActiveMQSubscriber
{
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    private static IConnectionFactory connFac;
    private static IConnection connection;
    private static ISession session;
    private static IDestination destination;
    private static IMessageProducer producer;
    private static IMessageConsumer consumer;
    protected static ITextMessage message = null;
    public Window1()
    {
      InitializeComponent();
      initAMQ("MyFirstTopic");
    }
    private void initAMQ(String strTopicName)
    {
      try
      {
        connFac = new NMSConnectionFactory(new Uri("activemq:failover:(tcp://localhost:61616)"));
        //新建銜接
        //connection = connFac.CreateConnection("oa","oa");//設置銜接要用的用戶名、暗碼
        //假如你要耐久“定閱”,則須要設置ClientId,如許法式運轉傍邊被停滯,恢復運轉時,能拿到沒吸收到的新聞!
        connection.ClientId = "testing listener";
        connection = connFac.CreateConnection();//假如你是缺省方法啟動Active MQ辦事,則不需填用戶名、暗碼
        //創立Session
        session = connection.CreateSession();
        //宣布/定閱形式,合適一對多的情形
        destination = SessionUtil.GetDestination(session, "topic://" + strTopicName);
        //新建臨盆者對象
        producer = session.CreateProducer(destination);
        producer.DeliveryMode = MsgDeliveryMode.NonPersistent;//ActiveMQ辦事器停滯任務後,新聞不再保存
        //新建花費者對象:通俗“定閱”形式
        //consumer = session.CreateConsumer(destination);//不須要耐久“定閱”
        //新建花費者對象:耐久"定閱"形式:
        //  耐久“定閱”後,假如你的法式被停滯任務後,恢復運轉,
        //從第一次耐久定閱開端,充公到的新聞還可以持續收
        consumer = session.CreateDurableConsumer(
          session.GetTopic(strTopicName)
          , connection.ClientId, null, false);
        //設置新聞吸收事宜
        consumer.Listener += new MessageListener(OnMessage);
        //啟動來自Active MQ的新聞偵聽
        connection.Start();
      }
      catch (Exception e)
      {
        //初始化ActiveMQ銜接掉敗,往VS2008的Output窗口寫入失足信息!
        Debug.WriteLine(e.Message);
      }
    }
    private void SendMsg2Topic_Click(object sender, RoutedEventArgs e)
    {
      //發送新聞
      ITextMessage request = session.CreateTextMessage(DateTime.Now.ToLocalTime()+" "+tbMsg.Text);
      producer.Send(request);
    }
    protected void OnMessage(IMessage receivedMsg)
    {
      //吸收新聞
      message = receivedMsg as ITextMessage;
      //UI線程,顯示收到的新聞
      Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
      {
        DateTime dt = new DateTime();
        ListBoxItem lbi = new ListBoxItem();
        lbi.Content = DateTime.Now.ToLocalTime() + " " + message.Text;
        lbR.Items.Add(lbi);
      }));
    }
  }
}

隊列通信方法,花費者例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Apache.NMS;
using System.Diagnostics;
using log4net;
using Apache.NMS.Util;
using System.Collections;
namespace Cat8637AutoCallServer
{
  public class SMTask
  {
    public String Callee { get; set; }
    public String CheckNumber { get; set; }
    public int Deadline { get; set; }
    public override String ToString()
    {
      return String.Format("Callee={0},CheckNumber={1},Deadline={2}",
        Callee,CheckNumber,Deadline);
    }
  }
  /*
   * 擔任吸收義務,並把義務放在義務期待隊列中。
   */
  public class MQClient
  {
    private static readonly ILog logger = LogManager.GetLogger(typeof(MQClient));
    private static IConnection connection = null;
    private static ISession session = null;
    Queue _voiceSMTasks = new Queue();
    public MQClient()
    {
      try
      {
        IConnectionFactory factory = new NMSConnectionFactory(new Uri("activemq:failover:(tcp://localhost:61616)"));
        //新建銜接
        //connection = connFac.CreateConnection("oa","oa");//設置銜接要用的用戶名、暗碼
        connection = factory.CreateConnection();
        session = connection.CreateSession();
        IMessageConsumer consumer = session.CreateConsumer(session.GetQueue("TaskIssue_VoiceSM"));
        consumer.Listener += new MessageListener(OnMessage);
        connection.Start();
      }
      catch (Exception ex)
      {
        Debug.WriteLine(ex.Message);
      }
    }
    protected void OnMessage(IMessage receivedMsg)
    {
      IMessage message = receivedMsg as ITextMessage;
      SMTask smTask = new SMTask();
      smTask.Callee = message.Properties["Callee"] as String;
      smTask.CheckNumber = message.Properties["Message"] as String;
      smTask.Deadline = Convert.ToInt32(message.Properties["deadline"] as String);
      logger.Info("Received: "+smTask.ToString());
      lock (_voiceSMTasks)
      {
        _voiceSMTasks.Enqueue(smTask);
      }
    }
    public SMTask GetVoiceSMTask()
    {
      SMTask result = null;
      lock (_voiceSMTasks)
      {
        if (_voiceSMTasks.Count > 0)
        {
          result = _voiceSMTasks.Dequeue() as SMTask;
        }
      }
      return result;
    }
  }
}

隊列通信方法,臨盆者例子

private void Send_Click(object sender, RoutedEventArgs e)
{
  try
  {
    IDestination destination = SessionUtil.GetDestination(session, "queue://TaskIssue_VoiceSM");
    //新建臨盆者對象
    IMessageProducer producer = session.CreateProducer(destination);
    producer.DeliveryMode = MsgDeliveryMode.NonPersistent;//ActiveMQ辦事器停滯任務後,新聞不再保存
    ITextMessage request = session.CreateTextMessage();
    request.NMSCorrelationID = "TestVoiceSM";//這裡我填了運用法式的稱號。
    request.Properties["Callee"] = tbCallee.Text;
    request.Properties["Message"] = tbCheckNumber.Text;
    request.Properties["deadline"] = tbValidDuration.Text;
    producer.Send(request);
  }
  catch (Exception ex)
  {
    //初始化ActiveMQ銜接掉敗,往VS2008的Output窗口寫入失足信息!
    Debug.WriteLine(ex.Message);
  }
}
private void Window_Closed(object sender, EventArgs e)
{
  try
  {
    if (session == null)
      return;
    //if (connection == null)
    //  return;
    session.Close();
    //connection.Close();
  }
  catch (Exception ex)
  {
    Debug.WriteLine(ex.Message);
  }
}

願望本文所述對年夜家C#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved