一、理论:
.net环境下,C#代码调用RabbitMQ消息队列,本文用easynetq开源的.net Rabbitmq api来实现。
EasyNetQ 是一个易于使用的RabbitMQ的.Net客户端API。
RabbitMQ 是由 LShift 提供的一个 Advanced Message Queuing Protocol (AMQP) 的开源实现,由以高性能、健壮以及可伸缩性出名的 Erlang 写成,因此也是继承了这些优点。
AMQP 里主要要说两个组件:Exchange 和 Queue (在 AMQP 1.0 里还会有变动),
如下图所示,绿色的 X 就是 Exchange ,红色的是 Queue ,这两者都在 Server 端,又称作 Broker ,
这部分是 RabbitMQ 实现的,而蓝色的则是客户端,通常有 Producer 和 Consumer 两种类型:

二、asp.net项目搭建
1、新建项目(略)

2、项目nuget需要使用的三方dll,本文案例使用的版本如下图

3、消息队列类库结构说明

4、BusBuilder.cs管道创建类,主要负责链接Rabbitmq
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/// <summary>/// 消息服务器连接器/// </summary>public class BusBuilder{ public static IBus CreateMessageBus() { //消息服务器连接字符串 var connectionString = ConfigurationManager.ConnectionStrings["RabbitMQ"]; if (connectionString == null || connectionString.ConnectionString == string.Empty) { throw new Exception("messageserver connection string is missing or empty"); } return RabbitHutch.CreateBus(connectionString.ConnectionString); }} |
5、IProcessMessage类,定义了一个消息方法,用于消息传递
|
1
2
3
4
5
6
|
public interface IProcessMessage{ void ProcessMsg(Message msg); void Notice();} |
6、Message类,定义了消息传递的实体属性字段等信息
|
1
2
3
4
5
6
7
8
9
10
|
public class Message{ public string MessageID { get; set; } public string MessageTitle { get; set; } public string MessageBody { get; set; } public string MessageRouter { get; set; }} |
7、MQHelper类,负责创建消息管道、创建消息管道、发送消息体等工作
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/// <summary>/// 发送消息/// </summary>public static void Publish(Message msg){ //// 创建消息bus IBus bus = BusBuilder.CreateMessageBus(); try { using (var publishChannel = bus.OpenPublishChannel()) //创建消息管道 { publishChannel.Publish(msg, x => x.WithTopic(msg.MessageRouter)); //通过管道发送消息 } } catch (EasyNetQException ex) { //处理连接消息服务器异常 } bus.Dispose();//与数据库connection类似,使用后记得销毁bus对象} |
8、web项目进行调用后台消息队列方法
|
1
2
3
4
5
6
|
RabbitMQ.Message msg = new RabbitMQ.Message();msg.MessageID = "test";msg.MessageBody = DateTime.Now.ToString();msg.MessageTitle = "test";msg.MessageRouter = "pcm.notice.zhangsan";RabbitMQ.MQHelper.Publish(msg); |
这样就可以用c#发送消息到队列中,测试结果如下图:

查看队列下的消息记录

获取队列消息尝试

至此,C#向Rabbitmq消息队列发送消息已经简单完成