首先需要安装Erlang和Rabbitmq
  Erlang下载地址:https://www.erlang.org/downloads
  rabbitmq下载地址:https://www.rabbitmq.com/install-windows.html
安装成功后需要切换到Rabbitmq目录下执行如下命令配置Rabbitmq:
  rabbitmq-plugins.bat enable rabbitmq_management 然后可在浏览器中输入地址http://localhost:15672/进行服务端配置; 操作代码如下:
/// <summary>
/// 消费者(消息)
/// </summary>
public class CustmerMq
{
/// <summary>
/// 最大的队列数目 根据cpu 来
/// </summary>
private static int Maximum_number_queues = ;
private static int number = ; /// <summary>
/// 消费者(单个)
/// </summary>
/// <param name="url">RabbitMQ地址</param>
/// <param name="userName">登录名</param>
/// <param name="passWord">密码</param>
/// <param name="virtualHost">虚拟主机</param>
/// <param name="requestedHeartbeat">请求心跳,默认0</param>
/// <param name="queueName">队列名称</param>
/// <returns></returns>
public static string InitCustmerMqStr(string url, string userName, string passWord, string virtualHost, ushort requestedHeartbeat, string queueName)
{
var strMQ = string.Empty;
try
{
Uri uri = new Uri(url);//"amqp://172.16.11.148:5672/" //使用ConnectionFactory创建连接,虽然创建时指定了多个server address,但每个connection只与一个物理的server进行连接
ConnectionFactory cf = new ConnectionFactory(); cf.Endpoint = new AmqpTcpEndpoint(uri);
cf.UserName = userName; //"rollen";
cf.Password = passWord; //"root";
cf.VirtualHost = virtualHost; //"/";
cf.RequestedHeartbeat = requestedHeartbeat; //0; using (IConnection conn = cf.CreateConnection())
{
using (IModel ch = conn.CreateModel())
{
//普通使用方式BasicGet
//noAck = true,不需要回复,接收到消息后,queue上的消息就会清除
//noAck = false,需要回复,接收到消息后,queue上的消息不会被清除,直到调用channel.basicAck(deliveryTag, false); queue上的消息才会被清除 而且,在当前连接断开以前,其它客户端将不能收到此queue上的消息
BasicGetResult res = ch.BasicGet(queueName, false/*noAck*/);
if (res != null)
{
bool t = res.Redelivered;
t = true;
strMQ = System.Text.UTF8Encoding.UTF8.GetString(res.Body); ch.BasicAck(res.DeliveryTag, false);
}
}
}
}
catch (Exception ex)
{
Logger.Debug("RabbitMQ消费异常:" + ex.Message);
} return strMQ;
} /// <summary>
/// 消费者(遍历)
/// </summary>
/// <returns></returns>
public static object InitCustmerMqListT()
{
var url = ConfigurationManager.AppSettings["MQ_url_loan"];
var userName = ConfigurationManager.AppSettings["MQ_userName_loan"];
var passWord = ConfigurationManager.AppSettings["MQ_passWord_loan"];
var virtualHost = ConfigurationManager.AppSettings["MQ_virtualHost_loan"];
var requestedHeartbeat = ushort.Parse(ConfigurationManager.AppSettings["MQ_requestedHeartbeat_loan"] ?? "");
var queueName = ConfigurationManager.AppSettings["MQ_queueName_loan"]; return InitCustmerMqLists(url, userName, passWord, virtualHost, requestedHeartbeat, queueName);
} private static List<string> InitCustmerMqLists(string url, string userName, string passWord, string virtualHost, ushort requestedHeartbeat, string queueName)
{
var DeliveryTagList = new List<ulong>();
var list = new List<string>();
try
{
Uri uri = new Uri(url);//使用ConnectionFactory创建连接,虽然创建时指定了多个server address,但每个connection只与一个物理的server进行连接
ConnectionFactory cf = new ConnectionFactory(); cf.Endpoint = new AmqpTcpEndpoint(uri);
cf.UserName = userName; //"rollen";
cf.Password = passWord; //"root";
cf.VirtualHost = virtualHost; //"/";
cf.RequestedHeartbeat = requestedHeartbeat; //0; int ErrorSum = ; using (IConnection conn = cf.CreateConnection())
{ using (IModel ch = conn.CreateModel())
{
#region 清除队列消息
//var consumer = new QueueingBasicConsumer(ch); //ch.BasicConsume(queueName, noAck: true, consumer: consumer); //var msgResponse = consumer.Queue.Dequeue(); //blocking //ch.BasicAck(msgResponse.DeliveryTag, false);
#endregion //ch.BasicQos(0, 1, false);//这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message。换句话说,在接收到该Consumer的ack前,他它不会将新的Message分发给它。
#region 遍历消息队列获取消息
int k = ;
while (k < )
{
BasicGetResult res = ch.BasicGet(queueName, false/*noAck*/);
if (res != null)
{
try
{
var body = System.Text.UTF8Encoding.UTF8.GetString(res.Body);
list.Add(body);
DeliveryTagList.Add(res.DeliveryTag);
}
catch (Exception ex)
{
Logger.Debug("RabbitMQ消费异常:" + ex.Message);
if (ErrorSum >= )
{
break;
}
ErrorSum++;
}
}
else
{
break;
}
k++;
}
#endregion #region 消费完成,删除队列
try
{
if (DeliveryTagList != null && DeliveryTagList.Count > )
{
for (int i = ; i < DeliveryTagList.Count; i++)
{
ch.BasicAck(DeliveryTagList[i], false);
}
}
}
catch (Exception ex)
{
Logger.Debug("RabbitMQ消费异常:" + ex.Message);
}
#endregion ch.Close();
}
conn.Close();
}
}
catch (Exception ex)
{
Logger.Debug("RabbitMQ消费异常:" + ex.Message);
}
return list;
}
}
/// <summary>
/// 产生消息
/// </summary>
public class ProducerMQ
{
/// <summary>
/// 消息添加入队列
/// </summary>
/// <param name="str">消息内容</param>
/// <param name="url">消息队列服务器地址</param>
/// <param name="exchange">交换方式名称</param>
/// <param name="exchangeType">方式类型</param>
/// <param name="routingKey">方式Key</param>
/// <param name="userName">登录名称</param>
/// <param name="passWord">密码</param>
/// <param name="virtualHost">虚拟主机名</param>
/// <param name="requestedHeartbeat">请求心跳,默认0</param>
/// <param name="queueName">队列名称</param>
public static void InitProducerMQ(string str, string url, string exchange, string exchangeType, string routingKey, string userName, string passWord, string virtualHost, ushort requestedHeartbeat, string queueName)
{
//定义要链接的rabbitmq-server地址(基于amqp协议)
//Uri uri = new Uri("amqp://172.16.11.148:5672/");
Uri uri = new Uri(url);
//定义交换方式
//是否对消息队列持久化保存
bool persistMode = true;
//使用ConnectionFactory创建连接,虽然创建时指定了多个server address,但每个connection只与一个物理的server进行连接
ConnectionFactory cf = new ConnectionFactory(); cf.UserName = userName;
cf.Password = passWord; //cf.VirtualHost = "/";
cf.VirtualHost = virtualHost;
cf.RequestedHeartbeat = requestedHeartbeat;
cf.Endpoint = new AmqpTcpEndpoint(uri); //实例化IConnection对象,并设置交换方式
using (IConnection conn = cf.CreateConnection())
{
using (IModel ch = conn.CreateModel())
{
if (exchangeType != null)
{
//交换机持久化
ch.ExchangeDeclare(exchange, exchangeType, true);//,true,true,false,false, true,null);
////队列持久化
ch.QueueDeclare(queueName, true, false, false, null);
//ch.QueueBind("q2", "ex2", "m1");
ch.QueueBind(queueName, exchange, routingKey);
} //构造消息实体对象并发布到消息队列上
IMapMessageBuilder b = new MapMessageBuilder(ch);
if (persistMode)
{
//数据持久化
((IBasicProperties)b.GetContentHeader()).DeliveryMode = ;
} ////简单发布方式
ch.BasicPublish(exchange, routingKey,
(IBasicProperties)b.GetContentHeader(),
Encoding.UTF8.GetBytes(str));
ch.Close();
}
conn.Close();
}
} /// <summary>
/// 消息添加入队列
/// </summary>
/// <param name="model">消息内容</param>
public static void InitProducerMQ(object model)
{
try
{
var Is_RabbitMQ = ConfigurationManager.AppSettings["Is_RabbitMQ"] == null ? : Convert.ToInt32(ConfigurationManager.AppSettings["Is_RabbitMQ"].ToString());//是否开启队列
if (Is_RabbitMQ == )
{
var url = ConfigurationManager.AppSettings["RabbitMQ_url"] == null ? "amqp://172.16.5.180:5672/" : ConfigurationManager.AppSettings["RabbitMQ_url"].ToString();//消息队列服务器地址
var exchange = ConfigurationManager.AppSettings["RabbitMQ_exchange"] == null ? "WebApi" : ConfigurationManager.AppSettings["RabbitMQ_exchange"].ToString();//交换方式名称
var exchangeType = ConfigurationManager.AppSettings["RabbitMQ_exchangeType"] == null ? "direct" : ConfigurationManager.AppSettings["RabbitMQ_exchangeType"].ToString();//方式类型
var routingKey = ConfigurationManager.AppSettings["RabbitMQ_routingKey"] == null ? "XYJAPP" : ConfigurationManager.AppSettings["RabbitMQ_routingKey"].ToString();//方式Key
var userName = ConfigurationManager.AppSettings["RabbitMQ_userName"] == null ? "rollen" : ConfigurationManager.AppSettings["RabbitMQ_userName"].ToString();//登录名称
var passWord = ConfigurationManager.AppSettings["RabbitMQ_passWord"] == null ? "" : ConfigurationManager.AppSettings["RabbitMQ_passWord"].ToString();//密码
var virtualHost = ConfigurationManager.AppSettings["RabbitMQ_virtualHost"] == null ? "/" : ConfigurationManager.AppSettings["RabbitMQ_virtualHost"].ToString();//虚拟主机名
ushort requestedHeartbeat = ConfigurationManager.AppSettings["RabbitMQ_requestedHeartbeat"] == null ? ushort.Parse("") : Convert.ToUInt16(ConfigurationManager.AppSettings["RabbitMQ_requestedHeartbeat"].ToString());//请求心跳,默认0
var queueName = ConfigurationManager.AppSettings["RabbitMQ_queueName"] == null ? "APP" : ConfigurationManager.AppSettings["RabbitMQ_queueName"].ToString();//队列名称
var str = JsonConvert.SerializeObject(model); if (!string.IsNullOrWhiteSpace(str))
{
InitProducerMQ(str, url, exchange, exchangeType, routingKey, userName, passWord, virtualHost, requestedHeartbeat, queueName);
}
}
}
catch (Exception ex)
{
//Logger.Error("ProducerMQ", ex);
}
} /// <summary>
/// 消息添加入队列
/// </summary>
/// <param name="str">消息内容</param>
public static void InitProducerMQ(string str)
{
try
{
var Is_RabbitMQ = ConfigurationManager.AppSettings["Is_RabbitMQ"] == null ? : Convert.ToInt32(ConfigurationManager.AppSettings["Is_RabbitMQ"].ToString());//是否开启队列
if (Is_RabbitMQ == )
{
var url = ConfigurationManager.AppSettings["RabbitMQ_url"] == null ? "amqp://172.16.5.180:5672/" : ConfigurationManager.AppSettings["RabbitMQ_url"].ToString();//消息队列服务器地址
var exchange = ConfigurationManager.AppSettings["RabbitMQ_exchange"] == null ? "WebApi" : ConfigurationManager.AppSettings["RabbitMQ_exchange"].ToString();//交换方式名称
var exchangeType = ConfigurationManager.AppSettings["RabbitMQ_exchangeType"] == null ? "direct" : ConfigurationManager.AppSettings["RabbitMQ_exchangeType"].ToString();//方式类型
var routingKey = ConfigurationManager.AppSettings["RabbitMQ_routingKey"] == null ? "XYJAPP" : ConfigurationManager.AppSettings["RabbitMQ_routingKey"].ToString();//方式Key
var userName = ConfigurationManager.AppSettings["RabbitMQ_userName"] == null ? "rollen" : ConfigurationManager.AppSettings["RabbitMQ_userName"].ToString();//登录名称
var passWord = ConfigurationManager.AppSettings["RabbitMQ_passWord"] == null ? "" : ConfigurationManager.AppSettings["RabbitMQ_passWord"].ToString();//密码
var virtualHost = ConfigurationManager.AppSettings["RabbitMQ_virtualHost"] == null ? "/" : ConfigurationManager.AppSettings["RabbitMQ_virtualHost"].ToString();//虚拟主机名
ushort requestedHeartbeat = ConfigurationManager.AppSettings["RabbitMQ_requestedHeartbeat"] == null ? ushort.Parse("") : Convert.ToUInt16(ConfigurationManager.AppSettings["RabbitMQ_requestedHeartbeat"].ToString());//请求心跳,默认0
var queueName = ConfigurationManager.AppSettings["RabbitMQ_queueName"] == null ? "APP" : ConfigurationManager.AppSettings["RabbitMQ_queueName"].ToString();//队列名称 if (!string.IsNullOrWhiteSpace(str))
{
InitProducerMQ(str, url, exchange, exchangeType, routingKey, userName, passWord, virtualHost, requestedHeartbeat, queueName);
}
}
}
catch (Exception ex)
{
//Logger.Error("ProducerMQ", ex);
}
} /// <summary>
/// 添加入账内容进入队列
/// </summary>
/// <param name="model">消息内容</param>
public static void InitProducerLoanMQ(object model)
{
try
{
var Is_MQ = ConfigurationManager.AppSettings["Is_MQ_loan"] == null ? : Convert.ToInt32(ConfigurationManager.AppSettings["Is_MQ_loan"].ToString());//是否开启队列
if (Is_MQ == )
{
var url = ConfigurationManager.AppSettings["MQ_url_loan"] == null ? "amqp://172.16.5.180:5672/" : ConfigurationManager.AppSettings["MQ_url_loan"].ToString();//消息队列服务器地址
var exchange = ConfigurationManager.AppSettings["MQ_exchange_loan"] == null ? "WebApi" : ConfigurationManager.AppSettings["MQ_exchange_loan"].ToString();//交换方式名称
var exchangeType = ConfigurationManager.AppSettings["MQ_exchangeType_loan"] == null ? "direct" : ConfigurationManager.AppSettings["MQ_exchangeType_loan"].ToString();//方式类型
var routingKey = ConfigurationManager.AppSettings["MQ_routingKey_loan"] == null ? "XYJAPP" : ConfigurationManager.AppSettings["MQ_routingKey_loan"].ToString();//方式Key
var userName = ConfigurationManager.AppSettings["MQ_userName_loan"] == null ? "rollen" : ConfigurationManager.AppSettings["MQ_userName_loan"].ToString();//登录名称
var passWord = ConfigurationManager.AppSettings["MQ_passWord_loan"] == null ? "" : ConfigurationManager.AppSettings["MQ_passWord_loan"].ToString();//密码
var virtualHost = ConfigurationManager.AppSettings["MQ_virtualHost_loan"] == null ? "/" : ConfigurationManager.AppSettings["MQ_virtualHost_loan"].ToString();//虚拟主机名
ushort requestedHeartbeat = ConfigurationManager.AppSettings["MQ_requestedHeartbeat_loan"] == null ? ushort.Parse("") : Convert.ToUInt16(ConfigurationManager.AppSettings["MQ_requestedHeartbeat_loan"].ToString());//请求心跳,默认0
var queueName = ConfigurationManager.AppSettings["MQ_queueName_loan"] == null ? "APP" : ConfigurationManager.AppSettings["MQ_queueName_loan"].ToString();//队列名称
var str = JsonConvert.SerializeObject(model); if (!string.IsNullOrWhiteSpace(str))
{
InitProducerMQ(str, url, exchange, exchangeType, routingKey, userName, passWord, virtualHost, requestedHeartbeat, queueName);
}
}
}
catch (Exception ex)
{
//Logger.Error("ProducerMQ", ex);
}
}
}

以上为MQ生产者和消费者代码,引用以上代码必须添加引用RabbitMQ.Client.dll

RabbitMQ操作方法的更多相关文章

  1. 队列工厂之RabbitMQ

    本次和大家分享的是RabbitMQ队列的用法,前一篇文章队列工厂之(MSMQ)中在描述的时候已经搭建了简单工厂,因此本章内容是在其之上扩充的子项不再过多讲解工厂的代码了:RabbitMQ应该是现在互联 ...

  2. RabbitMQ系列教程之七:RabbitMQ的 C# 客户端 API 的简介

    今天这篇博文是我翻译的RabbitMQ的最后一篇文章了,介绍一下RabbitMQ的C#开发的接口.好了,言归正传吧. Net/C# 客户端 API简介1.主要的命名空间,接口和类  定义核心的API的 ...

  3. Asp.NetCore轻松学-实现一个轻量级高可复用的RabbitMQ客户端

    前言 本示例通过对服务订阅的封装.隐藏细节实现.统一配置.自动重连.异常处理等各个方面来打造一个简单易用的 RabbitMQ 工厂:本文适合适合有一定 RabbitMQ 使用经验的读者阅读,如果你还没 ...

  4. 【c#】RabbitMQ学习文档(七)C# API

    今天这篇博文是我翻译的RabbitMQ的最后一篇文章了,介绍一下RabbitMQ的C#开发的接口.好了,言归正传吧. Net/C# 客户端 API简介 主要的命名空间,接口和类 定义核心的API的接口 ...

  5. Docker部署Django项目+Nginx+Fluend日志收集 和redis、memcached、RabbitMQ、Celery

    前言 一.docker 1.docker是什么? Docker的英文本意是“搬运工”,Docker搬运的是集装箱(Container)可以成为容器,我可以把写的Django的WEB应用以及Python ...

  6. 初识RabbitMQ

    1.安装 rabbitmq官网:http://www.rabbitmq.com/ 下载地址:https://packagecloud.io/rabbitmq 下载rabbitmq-server 安装脚 ...

  7. RabbitMQ系列教程之七:RabbitMQ的 C# 客户端 API 的简介(转载)

    RabbitMQ系列教程之七:RabbitMQ的 C# 客户端 API 的简介 今天这篇博文是我翻译的RabbitMQ的最后一篇文章了,介绍一下RabbitMQ的C#开发的接口.好了,言归正传吧. N ...

  8. 杂项之rabbitmq

    杂项之rabbitmq 本节内容 rabbitmq简介 AMQP协议 rabbitmq使用 应用举例 rabbitmq简介 介绍rabbitmq之前,先介绍一下AMQP协议,因为rabbitmq就是基 ...

  9. .Net Core 商城微服务项目系列(七):使用消息队列(RabbitMQ)实现服务异步通信

    RabbitMQ是什么,怎么使用我就不介绍了,大家可以到园子里搜一下教程.本篇的重点在于实现服务与服务之间的异步通信. 首先说一下为什么要使用消息队列来实现服务通信:1.提高接口并发能力.  2.保证 ...

随机推荐

  1. 深入Guerrilla Games解密次世代开山大作《杀戮地带暗影坠落》(The technology of Killzone Shadow Fall)

    文章摘要:这几天终于有时间,把全文翻译完了,自己感觉不是太满意,不过大家能看懂就好,就当一个学习的机会.整篇文章通过SONY第一方游戏工作室Guerrilla Games主创的语录,为我们展现了次世代 ...

  2. linux, windows, mac, ios等平台GCC预编译宏判断

    写跨平台c/c++程序的时候,需要搞清各平台下面的预编译宏,区分各平台代码.而跨平台c/c++编程,GCC基本在各平台都可以使用.整理了一份各平台预编译宏的判断示例. 需要注意几点: * window ...

  3. 开发Wordpress主题时没有特色图片的功能

    在自己开发Wordpress主题的时候,发现右下方没有了之前见到的特色图片(Featured Image)功能模块 1.找到后台右上方的显示选项模块,下拉之后启用即可 2.如果以上步骤找不到该选项,那 ...

  4. linux rsync-文件同步和数据传输工具

    一.rsync的概述 rsync是类unix系统下的数据镜像备份工具,从软件的命名上就可以看出来了——remote sync.rsync是Linux系统下的文件同步和数据传输工具,它采用“rsync” ...

  5. Linux系统中的wc

    Linux系统中的wc(Word Count)命令的功能为统计指定文件中的字节数.字数.行数,并将统计结果显示输出. 1.命令格式: wc [选项]文件... 2.命令功能: 统计指定文件中的字节数. ...

  6. 【解题报告】[动态规划]-PID69 / 过河卒

    原题地址:http://www.rqnoj.cn/problem/69 解题思路: 用DP[i][j]表示到达(i,j)点的路径数,则 DP[0][0]=1 DP[i][j]=DP[i-1][j]+D ...

  7. 拦截器springmvc防止表单重复提交【2】

    [参考博客:http://my.oschina.net/mushui/blog/143397] 原理:在新建页面中Session保存token随机码,当保存时验证,通过后删除,当再次点击保存时由于服务 ...

  8. hibernate的级联(hibernate注解的CascadeType属性)

    [自己项目遇到的问题]: 新增  删除都可以实现 ,就是修改的时候无法同步更新设计三个类:  问题类scask  正文内容类text类    查看数+回复数+讨论数的runinfo类 [正文类和查看数 ...

  9. c++线程同步和通信

    一.线程的创建 你也许会说我一直用CreateThread来创建线程,一直都工作得好好的,为什么要用_beginthreadex来代替CreateThread,下面让我来告诉你为什么.    回答一个 ...

  10. jenkins部署应用

    1.    系统介绍 Jenkins系统提供了一键部署的作用,整个过程有从提测的分支抓取代码,编译,打包,把打的包部署在应用服务器上,基本有Service,Web和Worker等. 2.    Jen ...