MQ的调用
mq调用(相关dll)
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MqTest2
{
class Program
{ static void Main(string[] args)
{ }
/// <summary>
/// 获取数据
/// </summary>
static public void GetData()
{
MqHelper mqHelper = new MqHelper();
var e = mqHelper.GetMQMsg();
byte[] data = null;
if (e !=null)
{
data = e.Body;
var result = Encoding.UTF8.GetString(data);
}
}
/// <summary>
/// 发送数据
/// </summary>
static public void SendData()
{
MqHelper mqHelper = new MqHelper();
Student student = new Student()
{
name = "测试",
Age = ""
};
string errorMsg = string.Empty;
mqHelper.sendMQMessage(student, out errorMsg);//发送数据
}
} public class Student
{ public string name { get; set; } public string Age { get; set; }
} }
mq帮助类
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace MqTest2
{
class MqHelper
{
private IModel _channel;
private QueueingBasicConsumer _consumer;
private IDictionary<string, IModel> _channels;
public RabbitMQConfigSection_New RabbitMQConfigSection { get; private set; }
private readonly object _syncRoot = new object();
public ConnectionFactory Factory { get; private set; }
private IConnection Connection { get; set; }
string RoutingKeys = "CDP.Finish";//路由键(多个路由中间用,隔开)
string QueueName = "Citms.Queue.VideoTest";//队列名称
string ExchangeName = "Citms.Exchange.Test";//交换机名称
string SendRoutingKey = "CDP.Finish";//发送路由键 public MqHelper()
{
this._channels = new Dictionary<string, IModel>();
this.RabbitMQConfigSection = new RabbitMQConfigSection_New();
Factory = new ConnectionFactory();
Factory.UserName = this.RabbitMQConfigSection.RabbitMQUserName;
Factory.Password = this.RabbitMQConfigSection.RabbitMQPassword;
Factory.VirtualHost = "/";
Factory.Uri = this.RabbitMQConfigSection.RabbitMQUri;
CreateConsumer();
}
/// <summary>
/// 创建路由
/// </summary>
public void CreateConsumer()
{
try
{
_channel = GetNamedChannel(QueueName);
_channel.BasicQos(, , false);
GetChannel().QueueDeclare(QueueName, true, false, false, null);
if (!string.IsNullOrEmpty(RoutingKeys))
{
// 支持绑定多个路由键
string[] rks = RoutingKeys.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var rk in rks)
{
GetChannel().QueueBind(
QueueName,
ExchangeName,
rk.Trim()
);
}
}
this._consumer = new QueueingBasicConsumer(_channel);
_channel.BasicConsume(QueueName, false, this._consumer);
} catch (Exception ex)
{
throw (ex);
}
}
/// <summary>
/// 获取消息队列内容
/// </summary>
/// <returns></returns>
public BasicDeliverEventArgs GetMQMsg()
{
try
{
BasicDeliverEventArgs a;
bool status = this._consumer.Queue.Dequeue(, out a);//队列为空时结束挂起,不做这个判断当队列为空时会一直超时
if (status)
{
return a;
}
else
{
return null;
}
}
catch (Exception ex)
{ if (this._consumer == null || !this._consumer.IsRunning)
{
this.CreateConsumer();
}
throw;
}
}
/// <summary>
/// 发送队列消息
/// </summary>
/// <param name="iv"></param>
/// <param name="errorMsg"></param>
/// <returns></returns>
public bool sendMQMessage(Student iv, out string errorMsg)
{
errorMsg = "";
dynamic obj = new { DataType = "Student", Data = iv, ReportedTime = "" };
string value = JsonConvert.SerializeObject(obj);
try
{
lock (_channel)
{
_channel.ExchangeDeclare(ExchangeName, "direct", true);
byte[] bytes = Encoding.UTF8.GetBytes(value);
_channel.BasicPublish(ExchangeName, SendRoutingKey, null, bytes);
return true;
}
}
catch (Exception ex)
{
errorMsg = ex.Message;
return false;
}
}
/// <summary>
/// 获取 rabbitmq 通道
/// </summary>
/// <returns></returns>
public IModel GetChannel()
{
lock (this._syncRoot)
{
// 最多重试 4 次
for (int i = ; i < ; ++i)
{
try
{
// 通道为 null,重新创建
if (this._channel == null)
{
this._channel = this.GetConnection().CreateModel();
return this._channel;
}
// 通道不为 null,并且已经打开,直接返回
if (this._channel.IsOpen)
{
return this._channel;
}
// 通道不为 null,但是没有打开,关闭通道,continue
else
{
this._channel.Dispose();
this._channel = null;
// 随机休眠之后再试
int sleep = ;
Thread.Sleep(sleep);
continue;
}
}
catch (Exception ex)
{ }
finally
{ }
} return null;
}
}
/// <summary>
/// 获取命名通道.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public IModel GetNamedChannel(string name)
{
IModel channel;
lock (this._syncRoot)
{
for (int i = ; i < ; ++i)
{
try
{
// 通道为 null,重新创建
if (!this._channels.TryGetValue(name, out channel))
{
channel = this.GetConnection().CreateModel();
this._channels[name] = channel;
return channel;
}
// 通道不为 null,并且已经打开,直接返回
if (channel.IsOpen)
{
return channel;
}
// 通道不为 null,但是没有打开,关闭通道,continue
else
{
channel.Dispose();
channel = null;
this._channels.Remove(name);
// 随机休眠之后再试
int sleep = ;
Thread.Sleep(sleep);
continue;
}
}
catch (Exception ex)
{
throw;
}
finally
{ }
} return null;
}
}
public IConnection GetConnection()
{
lock (_syncRoot)
{
try
{
// 连接为 null,创建之
if (this.Connection == null)
{
if (this.Factory == null)
{ }
this.Connection = this.Factory.CreateConnection();
return this.Connection;
}
// 连接不为 null,但是状态不是已打开,关闭连接并重新创建连接
if (!this.Connection.IsOpen)
{
try
{
// 释放连接
this.Connection.Dispose();
this.Connection = null;
}
catch (Exception ex)
{
this.Connection = null;
}
finally
{
// 创建新连接
this.Connection = this.Factory.CreateConnection(); }
}
// 返回连接对象
return this.Connection;
}
catch (Exception ex)
{ throw ex;
}
}
} }
public class RabbitMQConfigSection_New
{ public string RabbitMQUri { get; set; } = "amqp://192.168.0.37:5672"; public string RabbitMQUserName { get; set; } = "citms"; public string RabbitMQPassword { get; set; } = "citms@b7";
}
}
MQ的调用的更多相关文章
- 使用rabbit mq.模拟dubbo,使MQ异步调用代码写起来像是同步方法.
最近在改造老系统,遇到了需要使用rabbitMq的场景.在以前使用的过程中需要在发送端和消费端各种配置,感觉比较麻烦,然后突然想到了dubbo中@Reference注解的形式,可不可以做一个类似的架子 ...
- .Net Core 商城微服务项目系列(十一):MQ消费端独立为Window服务+消息处理服务
之前使用MQ的时候是通过封装成dll发布Nuget包来使用,消息的发布和消费都耦合在使用的站点和服务里,这样会造成两个问题: 1.增加服务和站点的压力,因为每次消息的消费就意味着接口的调用,这部分的压 ...
- MQ脚本回放报错2059
1.响应2059错误 1.1. 涉及协议 MQ,调试回放阶段 1.2. 错误信息 完成码2原因为2059:未能为 '10.200.100.75:QMEMBFE' 创建 MQQueueManag ...
- java.lang.NoClassDefFoundError: Could not initialize class xxx 原因
一.问题及原因 程序里有个工具类,主要是调用它的静态方法来发送mq. 调用场景如下: 结果这两天报了个错: java.lang.NoClassDefFoundError: Could not init ...
- Kafka实践、升级和新版本(0.10)特性预研
本文来自于网易云社区 一.消息总线MQ和Kafka (挡在请求的第一线) 1. 几个应用场景 case a:上游系统往下游系统推送消息,而不关心处理结果: case b:一份新数据生成,需要实时保存到 ...
- ActiveMQ入门系列之应用:Springboot+ActiveMQ+JavaMail实现异步邮件发送
现在邮件发送功能已经是几乎每个系统或网址必备的功能了,从用户注册的确认到找回密码再到消息提醒,这些功能普遍的会用到邮件发送功能.我们都买过火车票,买完后会有邮件提醒,有时候邮件并不是买完票立马就能收到 ...
- 智能可视化搭建系统 Atom 服务架构演变
作者:凹凸曼 - Manjiz Atom 是什么?Atom 是集结业内各色资深电商行业设计师,提供一站式专业智能页面和小程序设计服务的平台.经过 2 年紧凑迭代,项目越来越庞大,需求不断变更优化,内部 ...
- 在.NET Core 中收集数据的几种方式
APM是一种应用性能监控工具,可以帮助理解系统行为, 用于分析性能问题的工具,以便发生故障的时候,能够快速定位和解决问题, 通过汇聚业务系统各处理环节的实时数据,分析业务系统各事务处理的交易路径和处理 ...
- SpringCloud(六)分布式事务
在分布式系统中,分布式事务基本上是绕不开的, 分布式事务是指事务的参与者.支持事务的服务器.资源服务器以及事务管理器分别位于不同的分布式系统的不同节点之上 .其实就可以简单理解成在分布式系统中实现事务 ...
随机推荐
- 模块学习--random
1 随机一个0-1之间float >>> random.random() 0.82544262519395 >>> random.random() 0.114854 ...
- Struts2报错异常Method "setUser" failed for object com.mikey.action.ConverterAction@dd34285
在写类型转换的时候发现报错 异常信息 ognl.MethodFailedException: Method "setUser" failed for object com.mike ...
- 为什么需要NAT,目前家庭的计算机器如何上网?(原创)
.什么是NAT? 字面翻译网络地址转换. 2.产生的背景 解决公网IP不足的问题. 官方规定,将IP地址资源进行分类,分为ABCDE,常用ABC三类,在每类中划分出了一些私有IP供 ...
- Java--输入与输入
输入 java.util.Scanner java.lang.System java.io.Console ``` Scanner in = new Scanner(System.in); // 新建 ...
- hdfs dfs ls /列出了本地根目录下文件夹和文件Warning: fs.defaultFS is not set when running "ls" command
[root@node01 customShells]# hdfs dfs -ls /Warning: fs.defaultFS is not set when running "ls&quo ...
- Educational Codeforces Round 72 (Rated for Div. 2)C(暴力)
#define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;char s[200007];int a[20 ...
- android.view.WindowManager$BadTokenException 崩掉
问题: 以前的项目,今天打开运行,Activity刚打开的时候,点开一个弹窗是好的,但是再点到另一个界面的时候,返回,再点弹窗就崩了. 解决: 网上查了一下,发现出现这个问题的还特别多,大体如下: 1 ...
- 已知空间三点组成的面求该面上某点的Z值
已知空间三点,那么可以就可以确定空间三点组成的平面.此时可以根据某一点的X值和Y值,来求取该点在平面上的Z值.这个过程对于求三角面片上某点的高程或者权值特别有用,其本身也可以看作一种线性插值. 其算法 ...
- 本周总结(19年暑假)—— Part7
日期:2019.8.25 博客期:113 星期日
- Eclipse中创建新的SpringBoot项目(打包并且部署到tomcat)
Spring-boot因为其对jar包的高度集成以及简化服务配置,快速部署等的优点,逐渐成为Java开发人员的热衷的框架.下面演示一下怎么在Eclipse中新建Spring-boot项目以及打包部署. ...