C # implements a method for communicating with active MQ _c# tutorial

Source: Internet
Author: User
Tags failover

The example in this article describes how C # implements the method of communicating with active MQ. Share to everyone for your reference, specific as follows:

Content Summary:

Mainly in the form of source code describes how to use C # to implement the communication with active MQ. This article assumes that you have properly installed jdk1.6.x, understand active MQ and have a certain programming base.

Body:

The ultimate goal of a JMS program is to produce and consume messages that can be used by other programs, and the JMS message is a simple and flexible basic format that allows you to create messages that are not in the JMS format on different platforms.
The message consists of the header, the attributes, and the message body three parts.
Active MQ supports filtering mechanism, that is, the producer can set the properties of the message, which corresponds to the selector of the consumer, and only the selector of the consumer setting matches the properties of the message, and the message is sent to the consumer. Both topic and queue support Selector.

Sample code:

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; * * Function Description: C # using ACTIVEMQ Sample * Modified: 2 * Last update: by kagula,2012-07-31 * * Prerequisites: * [1]apache-activemq-5.4.2 * [2]apache.nms . Activemq-1.5.6-bin * [3]winxp SP3 * [4]vs2008 SP1 * [5]WPF project with. NET Framework 3.5 * * * start * * Without a security control method to start * [Your decompression Path]\apache-activemq-5.4.2\bin\activemq.bat * * Secure way to start * Add environment variable: ACTIVEMQ_ENCRYPTION_PASSWORD=ACTIVEMQ * [Your decompression path]\ APACHE-ACTIVEMQ-5.4.2\BIN>ACTIVEMQ xbean:file:.
 /conf/activemq-security.xml * Active MQ Admin Address * http://127.0.0.1:8161/admin/* Add access to "http://127.0.0.1:8161/admin/" restrictions * * FirstStep: Add Access Restrictions * Modify D:\apache\apache-activemq-5.4.2\conf\jetty.xml file * Below this line code, original * <property name= "authenticate" value= "Tru" E "/> * modified to * <property name=" authenticate "value=" false "/> * * Step two: Modify the login username password, the default is Admin,admin * D:\apache\ Apache-activemq-5.4.2\conf\jetty-realm.properties * User Management (Prerequisite: Start activemq in a safe manner) * * In [Your decompression path]\apache-activemq-5.4.2\ Conf\credentials.properties file to modify the default username password * In [your decompression path]\apache-activemq-5.4.2\conf\
 Activemq-security.xml file can add a new user name * e.g. add OA user, password and username. * <authenticationuser username= "OA" password= "OA" groups= "Users,admins"/> * * in [Your decompression path]\apache-activemq-5.4.2\
 Conf\activemq-security.xml file You can also set the specified topic or queue * Only by which user group read or write. * * The [Application]->[targetframework] property of the C # with WPF Project * project is set to [. NETFramework 3.5] (this is the default setting for the VS2008WPF project) * Add [Your decompression path]\apache.nms.activemq-1.5.6-bin\lib\apache.nms\net-3.5\ Apache.NMS.dll Reference * Apache.NMS.dll equivalent to the interface * * If DEBUG is debugging * Put [your decompression path]\apache.nms.activemq-1.5.6-bin\build\net-3.5\deb In the ug\ directory
 * Apache.NMS.ActiveMQ.dll files copied to your project's debug directory * Apache.NMS.ActiveMQ.dll equivalent to implementation * * If you are debugging in release mode * Refer to the above, to fetch apache.nms,re
 Lease the corresponding DLL file in the directory and copy it to your project's release directory. * * reference * [1] "C # call ACTIVEMQ Official Example" http://activemq.apache.org/nms/examples.html * [2] "ACTIVEMQ NMS download Address" http://activemq Apache.org/nms/activemq-downloads.html * [3] Example of Active MQ application in C # http://www.jb51.net/article/87956.htm * [4] NMS API Reference "http://activemq.apache.org/nms/nms-api.html * * namespace Testactivemqsubscriber {///<summary>///I Nteraction logic for Window1.xaml///</summary> public partial class Window1:window {private static IC
    Onnectionfactory 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)")); New Connection//connection = Connfac.createconnection ("OA", "OA")//Set the username, password//If you want to persist "subscribe", you need to set the ClientID, so the program shipped
        The business is stopped, the resumption of operation, you can get the message did not receive! Connection.
        ClientId = "Testing listener"; Connection = Connfac.createconnection ();//If you are starting the active MQ service by default, you do not need to fill in the username, password//create session session = Connectio
        N.createsession ();
        Publish/Subscribe mode, suitable for a one-to-many situation destination = Sessionutil.getdestination (Session, "topic://" + strtopicname); New Producer Object producer = Session.
        Createproducer (destination); Producer. DeliveryMode = The message is no longer retained//new consumer object after the MSGDELIVERYMODE.NONPERSISTENT;//ACTIVEMQ server stops working: Normal subscription mode//consumer = ses Sion. Createconsumer (destination);/does not require persistent "subscribe"//New Consumer objects: Persistent "Subscription" mode://persistent "subscribe", if your program is stopped working after resuming operation,//From the beginning of the first persistent subscription, the confiscated message can continue to receive consumer = session. Createdurableconsumer (session. Gettopic (strtopicname), connection.
        ClientId, NULL, FALSE); Sets the message receive event consumer.
        Listener + = new MessageListener (OnMessage); Initiates a message listening connection from active MQ.
      Start ();
        catch (Exception e) {//Initialize ACTIVEMQ connection failed, write error message to VS2008 Output window!
      Debug.WriteLine (E.message); } private void Sendmsg2topic_click (object sender, RoutedEventArgs e) {//Send message Itextmessage reque St = Session.
      Createtextmessage (DateTime.Now.ToLocalTime () + "" +tbmsg.text); Producer.
    Send (Request);
      } protected void OnMessage (IMessage receivedmsg) {//Receive message = Receivedmsg as itextmessage; UI thread, which displays the message received 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);
    }));

 }
  }
}

Queue communication methods, consumer examples

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} '), call
    Ee,checknumber,deadline);
   }/* * is responsible for receiving tasks and placing tasks in the task wait queue.
    * * Public class Mqclient {private static readonly ILog logger = Logmanager.getlogger (typeof));
    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));
   New Connection     Connection = Connfac.createconnection ("OA", "OA")//Set the username, password connection = factory To use for the connection.
        CreateConnection (); Session = connection.
        CreateSession (); Imessageconsumer consumer = session. Createconsumer (session.
        Getqueue ("Taskissue_voicesm")); Consumer.
        Listener + = new MessageListener (OnMessage); Connection.
      Start (); The 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;

 }
  }
}

Queue communication methods, producer examples

private void Send_click (object sender, RoutedEventArgs e) {try {idestination destination = Sessionutil.getdesti
    Nation (Session, "QUEUE://TASKISSUE_VOICESM"); New Producer Object Imessageproducer producer = Session.
    Createproducer (destination); Producer. DeliveryMode = MSGDELIVERYMODE.NONPERSISTENT;//ACTIVEMQ Server stops working, messages are no longer reserved Itextmessage request = Session.
    Createtextmessage (); Request.
    Nmscorrelationid = "TESTVOICESM";//Here I fill in the name of the application. Request.
    properties["callee"] = Tbcallee.text; Request.
    properties["message"] = Tbchecknumber.text; Request.
    properties["deadline"] = Tbvalidduration.text; Producer.
  Send (Request);
    A catch (Exception ex) {//initialization ACTIVEMQ Connection failed to write an error message to the output window of VS2008! 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);

 }
}

Read more about C # Interested readers can view the site topics: "C # form Operation Tips Summary", "C # Common control usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Usage Skills summary", "C # Operation Excel Skills Summary", "C # Summary of operational skills in XML files, C # tutorial on data structure and algorithms, C # array operation techniques Summary, and C # Introduction to object-oriented Programming

I hope this article will help you with C # programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.