1、准备工具

VS2013Apache.NMS.ActiveMQ-1.7.2-bin.zip
apache-activemq-5.14.0-bin.zip

2、开始项目

VS2013新建一个C#控制台应用程序,项目中添加两个dll引用,一个是D:\Apache.NMS.ActiveMQ-1.7.2-bin\lib\Apache.NMS\net-4.0目录下的Apache.NMS.dll,另一个是D:\Apache.NMS.ActiveMQ-1.7.2-bin\build\net-4.0\debug目录下的Apache.NMS.ActiveMQ.dll。

新建一个类,MyActiveMq.cs,用于对activemq消息队列接口的封装,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Apache.NMS;
using Apache.NMS.ActiveMQ;
 
namespace NmsProducerClasses
{
    public class MyActiveMq
    {
        private IConnectionFactory factory;
        private IConnection connection;
        private ISession session;
        private IMessageProducer prod;
        private IMessageConsumer consumer;
        private ITextMessage msg;
 
        private bool isTopic = false;
        private bool hasSelector = false;
        private const string ClientID = "clientid";
        private const string Selector = "filter='demo'";
        private bool sendSuccess = true;
        private bool receiveSuccess = true;
 
        public MyActiveMq(bool isLocalMachine, string remoteAddress)
        {
            try
            {
                //初始化工厂  
                if (isLocalMachine)
                {
                    factory = new ConnectionFactory("tcp://localhost:61616/");
                }
                else
                {
                    factory = new ConnectionFactory("tcp://" + remoteAddress + ":61616/"); //写tcp://192.168.1.111:61616的形式连接其他服务器上的ActiveMQ服务器          
                }
                //通过工厂建立连接
                connection = factory.CreateConnection();
                connection.ClientId = ClientID;
                connection.Start();
                //通过连接创建Session会话
                session = connection.CreateSession();
            }
            catch (System.Exception e)
            {
                sendSuccess = false;
                receiveSuccess = false;
                Console.WriteLine("Exception:{0}", e.Message);
                Console.ReadLine();
                throw e;
            }
            Console.WriteLine("Begin connection...");
        }
 
 
        ~MyActiveMq()
        {
            //this.ShutDown();
        }
 
        /// <summary>
        /// 初始化
        /// </summary>
        ///<param name="topic">选择是否是Topic
        ///<param name="name">队列名
        ///<param name="selector">是否设置过滤
        public bool InitQueueOrTopic(bool topic, string name, bool selector = false)
        {
            try
            {
                //通过会话创建生产者、消费者
                if (topic)
                {
                    prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(name));
                    if (selector)
                    {
                        consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(name), ClientID, Selector, false);
                        hasSelector = true;
                    }
                    else
                    {
                        consumer = session.CreateDurableConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQTopic(name), ClientID, null, false);
                        hasSelector = false;
                    }
                    isTopic = true;
                }
                else
                {
                    prod = session.CreateProducer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(name));
                    if (selector)
                    {
                        consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(name), Selector);
                        hasSelector = true;
                    }
                    else
                    {
                        consumer = session.CreateConsumer(new Apache.NMS.ActiveMQ.Commands.ActiveMQQueue(name));
                        hasSelector = false;
                    }
                    isTopic = false;
                }
                //创建一个发送的消息对象
                msg = prod.CreateTextMessage();
            }
            catch (System.Exception e)
            {
                sendSuccess = false;
                receiveSuccess = false;
                Console.WriteLine("Exception:{0}", e.Message);
                Console.ReadLine();
                throw e;
            }
 
            return sendSuccess;
        }
 
 
        public bool SendMessage(string message, string msgId = "defult", MsgPriority priority = MsgPriority.Normal)
        {
            if (prod == null)
            {
                sendSuccess = false;
                Console.WriteLine("call InitQueueOrTopic() first!!");
                return false;
            }
 
            Console.WriteLine("Begin send messages...");
 
            //给这个对象赋实际的消息
            msg.NMSCorrelationID = msgId;
            msg.Properties["MyID"] = msgId;
            msg.NMSMessageId = msgId;
            msg.Text = message;
            Console.WriteLine(message);
 
            if (isTopic)
            {
                sendSuccess = ProducerSubcriber(message, priority);
            }
            else
            {
                sendSuccess = P2P(message, priority);
            }
 
            return sendSuccess;
        }
 
 
        public string GetMessage()
        {
            if (prod == null)
            {
                Console.WriteLine("call InitQueueOrTopic() first!!");
                return null;
            }
 
            Console.WriteLine("Begin receive messages...");
            ITextMessage revMessage = null;
            try
            {
                //同步阻塞10ms,没消息就直接返回null,注意此处时间不能设太短,否则还没取到消息就直接返回null了!!!
                revMessage = consumer.Receive(new TimeSpan(TimeSpan.TicksPerMillisecond *10)) as ITextMessage;
            }
            catch (System.Exception e)
            {
                receiveSuccess = false;
                Console.WriteLine("Exception:{0}", e.Message);
                Console.ReadLine();
                throw e;
            }
 
            if (revMessage == null)
            {
                Console.WriteLine("No message received!");
                return null;
            }
            else
            {
                Console.WriteLine("Received message with Correlation ID: " + revMessage.NMSCorrelationID);
                //Console.WriteLine("Received message with Properties'ID: " + revMessage.Properties["MyID"]);
                Console.WriteLine("Received message with text: " + revMessage.Text);
            }
 
            return revMessage.Text;
        }
 
        //P2P模式,一个生产者对应一个消费者
        private bool P2P(string message, MsgPriority priority)
        {
            try
            {
                if (hasSelector)
                {
                    //设置消息对象的属性,这个很重要,是Queue的过滤条件,也是P2P消息的唯一指定属性
                    msg.Properties.SetString("filter", "demo");  //P2P模式
                }
                prod.Priority = priority;
                //设置持久化
                prod.DeliveryMode = MsgDeliveryMode.Persistent;
                //生产者把消息发送出去,几个枚举参数MsgDeliveryMode是否持久化,MsgPriority消息优先级别,存活时间,当然还有其他重载
                prod.Send(msg, MsgDeliveryMode.Persistent, priority, TimeSpan.MinValue);
            }
            catch (System.Exception e)
            {
                sendSuccess = false;
                Console.WriteLine("Exception:{0}", e.Message);
                Console.ReadLine();
                throw e;
            }
 
            return sendSuccess;
        }
 
 
        //发布订阅模式,一个生产者多个消费者
        private bool ProducerSubcriber(string message, MsgPriority priority)
        {
            try
            {
                prod.Priority = priority;
                //设置持久化,如果DeliveryMode没有设置或者设置为NON_PERSISTENT,那么重启MQ之后消息就会丢失
                prod.DeliveryMode = MsgDeliveryMode.Persistent;
                prod.Send(msg, Apache.NMS.MsgDeliveryMode.Persistent, priority, TimeSpan.MinValue);
                //System.Threading.Thread.Sleep(1000); 
            }
            catch (System.Exception e)
            {
                sendSuccess = false;
                Console.WriteLine("Exception:{0}", e.Message);
                Console.ReadLine();
                throw e;
            }
 
            return sendSuccess;
        }
 
 
        public void ShutDown()
        {
            Console.WriteLine("Close connection and session...");
            session.Close();
            connection.Close();
        }
    }
}
Program.cs代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
 
namespace NmsProducerClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            MyActiveMq mymq = new MyActiveMq(isLocalMachine: true, remoteAddress: "");
 
            mymq.InitQueueOrTopic(topic: false, name: "myqueue", selector: false);
            //mymq.InitQueueOrTopic(topic: false, name: "seletorqueue", selector: true);
            //mymq.InitQueueOrTopic(topic: true, name: "noselectortopic", selector: false);
            //mymq.InitQueueOrTopic(topic: true, name: "selectortopic", selector: true);
 
            //The full range of priority values (0-9) are supported by the JDBC message store. For KahaDB three priority categories are supported, Low (< 4), Default (= 4) and High (> 4).
            User myuser0 = new User("0000", "Lowest", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser0), "newid", priority: Apache.NMS.MsgPriority.Lowest);
            User myuser1 = new User("1111", "AboveLow", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser1), "newid", priority: Apache.NMS.MsgPriority.AboveLow);
            User myuser2 = new User("2222", "AboveNormal", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser2), "newid", priority: Apache.NMS.MsgPriority.AboveNormal);
            User myuser3 = new User("0000", "BelowNormal", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser3), "newid", priority: Apache.NMS.MsgPriority.BelowNormal);
            User myuser4 = new User("1111", "High", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser4), "newid", priority: Apache.NMS.MsgPriority.High);
            User myuser5 = new User("2222", "Highest", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser5), "newid", priority: Apache.NMS.MsgPriority.Highest);
            User myuser6 = new User("0000", "Low", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser6), "newid", priority: Apache.NMS.MsgPriority.Low);
            User myuser7 = new User("1111", "Normal", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser7), "newid", priority: Apache.NMS.MsgPriority.Normal);
            User myuser8 = new User("2222", "VeryHigh", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser8), "newid", priority: Apache.NMS.MsgPriority.VeryHigh);
            User myuser9 = new User("2222", "VeryLow", "img/p.jpg");
            mymq.SendMessage(JsonUtil.ObjectToJson(myuser8), "newid", priority: Apache.NMS.MsgPriority.VeryLow);
 
            int num = 20;
            while (num-- > 0)
            {
                mymq.GetMessage();
                //Thread.Sleep(1000);
            }
            mymq.ShutDown();
             
 
            //XML测试
            //string xml = XmlTest.ObjToXml();
            //Console.WriteLine("ObjToXml: {0}", xml);
 
            //Json测试
            //User u = new User() { Id="88", Imgurl="img/88.jpg", Name="haha88"};
            //string jsonstr = JsonUtil.ObjectToJson(u);
            //Console.WriteLine(jsonstr);
             
        }
 
    }

3、测试

首先,需要启动消息队列,具体启动及测试消息队列步骤可见这边:点击打开链接

然后,运行项目,运行结果如下:

4、存在问题

priority并不能决定消息传送的严格消息,具体原因可见

ActiveMq C#客户端 消息队列的使用(存和取)的更多相关文章

  1. php 利用activeMq+stomp实现消息队列

    php 利用activeMq+stomp实现消息队列 一.activeMq概述 ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J ...

  2. 【ActiveMQ】持久化消息队列的三种方式

    1.ActiveMQ消息持久化方式,分别是:文件.mysql数据库.oracle数据库 2.修改方式: a.文件持久化: ActiveMQ默认的消息保存方式,一般如果没有修改过其他持久化方式的话可以不 ...

  3. 实战Spring4+ActiveMQ整合实现消息队列(生产者+消费者)

    引言: 最近公司做了一个以信息安全为主的项目,其中有一个业务需求就是,项目定时监控操作用户的行为,对于一些违规操作严重的行为,以发送邮件(ForMail)的形式进行邮件告警,可能是多人,也可能是一个人 ...

  4. activemq读取剩余消息队列中消息的数量

    先上原文链接: http://blog.csdn.net/bodybo/article/details/5647968  ActiveMQ在C#中的应用 ActiveMQ是个好东东,不必多说.Acti ...

  5. ActiveMQ 消息队列服务

      1 ActiveMQ简介 1.1 ActiveMQ是什么 ActiveMQ是一个消息队列应用服务器(推送服务器).支持JMS规范. 1.1.1 JMS概述 全称:Java Message Serv ...

  6. 消息队列与Kafka

    2019-04-09 关键词: 消息队列.为什么使用消息队列.消息队列的好处.消息队列的意义.Kafka是什么 本篇文章系本人就当前所掌握的知识关于 消息队列 与 kafka 知识点的一些简要介绍,不 ...

  7. java JMS消息队列

    http://blog.csdn.net/shirdrn/article/details/6362792 http://haohaoxuexi.iteye.com/blog/1893038 http: ...

  8. php消息队列

    Memcache 一般用于缓存服务.但是很多时候,比如一个消息广播系统,需要一个消息队列.直接从数据库取消息,负载往往不行.如果将整个消息队列用一个key缓存到memcache里面.对于一个很大的消息 ...

  9. 利用redis制作消息队列

    redis在游戏服务器中的使用初探(一) 环境搭建redis在游戏服务器中的使用初探(二) 客户端开源库选择redis在游戏服务器中的使用初探(三) 信息存储redis在游戏服务器中的使用初探(四) ...

随机推荐

  1. C#实现ATM自动取款机

    本篇用C#实现ATM自动取款机的一些功能.面临的第一个问题是:如何把与自动取款机相关的有形的.无形的方面抽象出来.大致如下: (1)关于用户帐号的类:Account(2)关于银行数据库的类:BankD ...

  2. java代码声明引用变量经验

    1.static只能修饰类的成员变量,不能修饰方法里的局部变量. 因为static是在类加载时候将成员变量存储进方法区的. 加载类的时候,是不去执行方法里的函数的.所以不会馆方法里的代码,自然就不会读 ...

  3. 设置SVN忽略文件和目录(文件夹)

    在多数项目中你总会有文件和目录不需要进行版本控制.这可能包括一些由编译器生成的文件,*.obj,*.lst,或许是一个用于存放可执行程序的输出文件夹.只要你提交修改,TortoiseSVN 就会在提交 ...

  4. ios 重用UI部分代码的好方法(再也不用为局部变量的命名而烦恼啦!)

    重用控件类代码的一个非常好的解决方案:所有一样的控件其名字均用同样的一个名字.只是在最后赋值的时候,将创建好的控件赋给我们需要用到的那个控件. - (id)initWithFrame:(CGRect) ...

  5. ARC 特性

    ResultVC *myResultVC = [[ResultVC alloc]initWithNibName:@"ResultVC" bundle:nil]; [self.vie ...

  6. 使用线程安全的 MSWeakTimer ,它不会对目标进行retain操作,避免循环引用

    MSWeakTimer 简易翻译:该timer没有runloop概念,线程安全,没有循环引用现象. https://github.com/mindsnacks/MSWeakTimer Descript ...

  7. Asp.Net中自以为是的Encode

    Asp.Net 引擎可能是不错,但是它把程序员想的太笨,会自以为是做很多自动的 Encode 和 Decode,以下文举例: 如果客户端我们 post 了如下的数据, 但是你实际得到的是: 也就是说, ...

  8. [19] 半球形(Hemisphere)图形的生成算法

    顶点数据的生成 bool YfBuildHemisphereVertices ( Yreal radius, Yuint slices, Yuint stacks, YeOriginPose orig ...

  9. C/C++/Java 程序计时功能函数

    编写程序肯定要使用计时功能,来判断程序的执行时间.今天Google了一下,自己就梳理总结一下: (1)C/C++程序计时 C/C++中使用的计时函数是clock(). C语言中的头文件对应是#incl ...

  10. go语言基础之不要操作没有合法指向的内存

    1.不要操作没有合法指向的内存 示例: package main //必须有个main包 import "fmt" func main() { //没有指向内存 var p *in ...