C#使用ActiveMQ实例


参考网址:

1. ActiveMQ消息总线简介

消息队列(Message Queue,简称MQ),从字面意思上看,本质是个队列,FIFO先入先出,只不过队列中存放的内容是message而已。主要用作不同进程、应用间的通信方式。

常见的消息队列有:rabbitMQ、activeMQ、zeroMQ、Kafka、Redis 比较 。

其中ActiveMQ是Apache出品的一款开源消息总线,支持多种语言和协议编写客户端。语言: Java,C,C++,C#,Ruby,Perl,Python,PHP。应用协议: OpenWire,Stomp REST,WS Notification,XMPP,AMQP。

ActiveMQ主要有两种消息分发方式:Queue和Topic。

  Queue类似编程语言中的Queue,每条消息只会被一个消费者接收;

  Topic类似广播,发送的消息会被多个消费者接受,前提是订阅了该主题的消息。

2. ActiveMQ安装 

2.1. 下载ActiveMQ 

官方网站下载地址:http://activemq.apache.org/ 

2.2. 运行ActiveMQ 

解压缩apache-activemq-5.10.0-bin.zip,然后双击apache-activemq-5.10.0\bin\win32\activemq.bat运行ActiveMQ程序。 

看见控制台最后一行输出: “access to all MBeans is allowed” 证明启动成功。 

启动ActiveMQ以后,可以使用浏览器登陆:http://localhost:8161/admin/验证, 默认用户名是:admin  密码是:admin 

(前提是安装好Java环境) 

同时下载.net版Dll:Apache.NMS-1.7.0-bin.zip和Apache.NMS.ActiveMQ-1.7.0-bin.zip 

都从这里下载:http://archive.apache.org/dist/activemq/apache-nms/1.7.0/ 

3. ActiveMQ Queue

在ActiveMQ中Queue是一种点对点的消息分发方式,生产者在队列中添加一条消息,然后消费者消费一条消息,这条消息保证送达并且只会被一个消费者接收

这里使用Winform编写程序,其中需要添加两个dll,都在Apache.NMS-1.7.0-bin.zip和Apache.NMS.ActiveMQ-1.7.0-bin.zip中。 

// 生产者
// 需要添加一个label, button, textbox 
public Form1()
        {
            InitializeComponent();
            InitProducer();
        }
        private IConnectionFactory factory;

        public void InitProducer()
        {
            try
            {
                //初始化工厂,这里默认的URL是不需要修改的
                factory = new  ConnectionFactory("tcp://localhost:61616");

            }
            catch
            {
                lbMessage.Text = "初始化失败!!";
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            //通过工厂建立连接
            using (IConnection connection = factory.CreateConnection())
            {
                //通过连接创建Session会话
                using (ISession session = connection.CreateSession())
                {
                    //通过会话创建生产者,方法里面new出来的是MQ中的Queue
                    IMessageProducer prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"));
                    //创建一个发送的消息对象
                    ITextMessage message = prod.CreateTextMessage();
                    //给这个对象赋实际的消息
                    message.Text = txtMessage.Text;
                    //设置消息对象的属性,这个很重要哦,是Queue的过滤条件,也是P2P消息的唯一指定属性
                    message.Properties.SetString("filter","demo");
                    //生产者把消息发送出去,几个枚举参数MsgDeliveryMode是否长链,MsgPriority消息优先级别,发送最小单位,当然还有其他重载
                    prod.Send(message, MsgDeliveryMode.NonPersistent, MsgPriority.Normal, TimeSpan.MinValue);
                    lbMessage.Text = "发送成功!!";
                    txtMessage.Text = "";
                    txtMessage.Focus();
                }
            }
        }
    // 消费者
     public Form1()
        {
            InitializeComponent();
            InitConsumer();

        }
         public void InitConsumer()
         {
             //创建连接工厂
             IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616");
             //通过工厂构建连接
             IConnection connection = factory.CreateConnection();
             //这个是连接的客户端名称标识
             connection.ClientId = "firstQueueListener";
             //启动连接,监听的话要主动启动连接
             connection.Start();
             //通过连接创建一个会话
             ISession session = connection.CreateSession();
             //通过会话创建一个消费者,这里就是Queue这种会话类型的监听参数设置
             IMessageConsumer consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue("firstQueue"), "filter='demo'");
             //注册监听事件
             consumer.Listener += new MessageListener(consumer_Listener);
             //connection.Stop();
             //connection.Close();  
 
         }
 
         void consumer_Listener(IMessage message)
         {
             ITextMessage msg = (ITextMessage)message;
             //异步调用下,否则无法回归主线程
             tbReceiveMessage.Invoke(new DelegateRevMessage(RevMessage),msg);
 
         }
 
         public delegate void DelegateRevMessage(ITextMessage message);
 
         public void RevMessage(ITextMessage message)
         {
             tbReceiveMessage.Text += string.Format(@"接收到:{0}{1}", message.Text, Environment.NewLine);
         }

我们可以到管理平台 http://localhost:8161 中查看对应的Queue,生产者产生消息,消费者接收后会删掉消息。

新建项目,更改 connection.ClientId 后可以启动多个消费者,可以发现每个消费者都有机会接收消息,测试的时候是每个消费者轮流接收一条消息,有兴趣的可以自己看一下接收规律。 

4. ActiveMQ Topic

Topic和Queue类似,不过生产者发送的消息会被多个消费者接收,保证每个订阅的消费者都会接收到消息。

在管理平台可以看到每条Topic消息有两个记录值,一个是订阅的消费者数量,一个是已经接收的消费者数量。

//生产者
try
{
    //Create the Connection Factory  
    IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");
    using (IConnection connection = factory.CreateConnection())
    {
        //Create the Session  
        using (ISession session = connection.CreateSession())
        {
            //Create the Producer for the topic/queue  
            IMessageProducer prod = session.CreateProducer(
                new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"));

            //Send Messages  
            int i = 0;

            while (!Console.KeyAvailable)
            {
                ITextMessage msg = prod.CreateTextMessage();
                msg.Text = i.ToString();
                Console.WriteLine("Sending: " + i.ToString());
                prod.Send(msg, Apache.NMS.MsgDeliveryMode.NonPersistent, Apache.NMS.MsgPriority.Normal, TimeSpan.MinValue);

                System.Threading.Thread.Sleep(5000);
                i++;
            }
        }
    }

    Console.ReadLine();
}
catch (System.Exception e)
{
    Console.WriteLine("{0}", e.Message);
    Console.ReadLine();
}
//消费者
static void Main(string[] args)
        {
            try  
            {  
                //Create the Connection factory  
                IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/");  
                  
                //Create the connection  
                using (IConnection connection = factory.CreateConnection())  
                {  
                    connection.ClientId = "testing listener1";  
                    connection.Start();  
  
                    //Create the Session  
                    using (ISession session = connection.CreateSession())  
                    {  
                        //Create the Consumer  
                        IMessageConsumer consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic("testing"), "testing listener1", null, false);  
                          
                        consumer.Listener += new MessageListener(consumer_Listener);  
  
                        Console.ReadLine();  
                    }  
                    connection.Stop();  
                    connection.Close();  
                }  
            }  
            catch (System.Exception e)  
            {  
                Console.WriteLine(e.Message);  
            }  
        }  
  
        static void consumer_Listener(IMessage message)  
        {  
            try  
            {  
                ITextMessage msg = (ITextMessage)message;  
                Console.WriteLine("Receive: " + msg.Text);  
           }  
            catch (System.Exception e)  
            {  
                Console.WriteLine(e.Message);  
            }  
        }

新建项目,更改connection.ClientId后可以启动多个消费者,可以发现每个消费者都会接收到消息,订阅一次后即使下线了,上线之后也会收到消息。

5. ActiveMQ持久化消息

ActiveMQ的另一个问题就是只要是软件就有可能挂掉,挂掉不可怕,怕的是挂掉之后把信息给丢了,所以本节分析一下几种持久化方式:

5.1 持久化为文件

ActiveMQ默认就支持这种方式,只要在发消息时设置消息为持久化就可以了。

打开安装目录下的配置文件:

D:\ActiveMQ\apache-activemq\conf\activemq.xml在越80行会发现默认的配置项:



     

注意这里使用的是kahaDB,是一个基于文件支持事务的消息存储器,是一个可靠,高性能,可扩展的消息存储器。

     他的设计初衷就是使用简单并尽可能的快。KahaDB的索引使用一个transaction log,并且所有的destination只使用一个index,有人测试表明:如果用于生产环境,支持1万个active connection,每个connection有一个独立的queue。该表现已经足矣应付大部分的需求。

然后再发送消息的时候改变第二个参数为:

MsgDeliveryMode.Persistent

Message保存方式有2种
PERSISTENT:保存到磁盘,consumer消费之后,message被删除。
NON_PERSISTENT:保存到内存,消费之后message被清除。
注意:堆积的消息太多可能导致内存溢出。

然后打开生产者端发送一个消息:

不启动消费者端,同时在管理界面查看:

发现有一个消息正在等待,这时如果没有持久化,ActiveMQ宕机后重启这个消息就是丢失,而我们现在修改为文件持久化,重启ActiveMQ后消费者仍然能够收到这个消息。

二、持久化为数据库

我们从支持Mysql为例,先从http://dev.mysql.com/downloads/connector/j/下载mysql-connector-java-5.1.34-bin.jar包放到:

D:\ActiveMQ\apache-activemq\lib目录下。

打开并修改配置文件:


 
    
    
        
            file:${activemq.conf}/credentials.properties
        
    
 
   
    
    
 
    
    
 
        
            
              
                
                    
                  
                    
                  
                
              
            
        
 
 
        
        
            
        
 
        
        
            
        
 
 
          
          
            
                
                    
                
                
                    
                
                
                    
                
            
        
 
        
        
            
            
            
            
            
            
        
 
        
        
            
        
 
    
  
    
    
    
    
    
    
  
    
    
 

重启ActiveMQ打开phpmyadmin发现多了3张表: 

然后启动生产者(不启动消费者) 

在Mysql中可以找到这条消息: 

关掉ActiveMQ并重启,模拟宕机。

然后启动消费者:

然后发现Mysql中已经没有这条消息了。

时间会记录下一切。   分类: 

相关