出处:https://www.cnblogs.com/hanfan/p/9842301.html

网上很多人已经总结的很好了,比如今天看到的这个。https://www.cnblogs.com/LipeiNet/p/9877189.html

我就不总结了,贴点代码。

RabbitMQConnect.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
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
using System;
using System.IO;
using System.Net.Sockets;
using Polly;
using Polly.Retry;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
 
namespace Common.Tool.RabbitMQ
{
    public class RabbitMQConnect
    {
         
        static string host = "127.0.0.1";
        static string UserName = "H";
        static string password = "H";
 
        public readonly static IConnectionFactory _connectionFactory;
        IConnection _connection;
        object sync_root = new object();
        bool _disposed;
        static RabbitMQConnect()
        {
            //if (host == "localhost")
            //{
            //    _connectionFactory = new ConnectionFactory() { HostName = host };
            //}
            //else
            {
                _connectionFactory = new ConnectionFactory() { HostName = host, UserName = UserName, Password = password };
            }
        }
        public bool IsConnected => this._connection != null && this._connection.IsOpen && this._disposed;
        public IModel CreateModel()
        {
            if (!this.IsConnected)
            {
                this.TryConnect();
            }
            return this._connection.CreateModel();
        }
        public bool TryConnect()
        {
            lock (this.sync_root)
            {
                RetryPolicy policy = RetryPolicy.Handle<SocketException>()//如果我们想指定处理多个异常类型通过OR即可
                    .Or<BrokerUnreachableException>()//ConnectionFactory.CreateConnection期间无法打开连接时抛出异常
                    .WaitAndRetry(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                        {
 
                        });// 重试次数,提供等待特定重试尝试的持续时间的函数,每次重试时调用的操作。
                policy.Execute(() =>
                {
                    this._connection = _connectionFactory.CreateConnection();
 
                });
 
                if (this.IsConnected)
                {
                    //当连接被破坏时引发。如果在添加事件处理程序时连接已经被销毁对于此事件,事件处理程序将立即被触发。
                    this._connection.ConnectionShutdown += this.OnConnectionShutdown;
                    //在连接调用的回调中发生异常时发出信号。当ConnectionShutdown处理程序抛出异常时,此事件将发出信号。如果将来有更多的事件出现在RabbitMQ.Client.IConnection上,那么这个事件当这些事件处理程序中的一个抛出异常时,它们将被标记。
                    this._connection.CallbackException += this.OnCallbackException;
                    this._connection.ConnectionBlocked += this.OnConnectionBlocked;
 
                    //LogHelperNLog.Info($"RabbitMQ persistent connection acquired a connection {_connection.Endpoint.HostName} and is subscribed to failure events");
 
                    return true;
                }
                else
                {
                    // LogHelperNLog.Info("FATAL ERROR: RabbitMQ connections could not be created and opened");
 
                    return false;
                }
            }
        }
 
        void OnConnectionShutdown(object sender, ShutdownEventArgs reason)
        {
            if (this._disposed) return;
            //RabbitMQ连接正在关闭。 尝试重新连接...
            //LogHelperNLog.Info("A RabbitMQ connection is on shutdown. Trying to re-connect...");
 
            this.TryConnect();
        }
        /// <summary>
        ///   
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnCallbackException(object sender, CallbackExceptionEventArgs e)
        {
            if (this._disposed) return;
 
            // LogHelperNLog.Info("A RabbitMQ connection throw exception. Trying to re-connect...");
 
            this.TryConnect();
        }
        private void OnConnectionBlocked(object sender, ConnectionBlockedEventArgs e)
        {
            if (this._disposed) return;
 
            //  LogHelperNLog.Info("A RabbitMQ connection is shutdown. Trying to re-connect...");
 
            this.TryConnect();
        }
 
        public void Dispose()
        {
            if (this._disposed) return;
 
            this._disposed = true;
 
            try
            {
                this._connection.Dispose();
            }
            catch (IOException ex)
            {
                //_logger.LogCritical(ex.ToString());
                //  LogHelperNLog.Error(ex);
            }
        }
    }
}

  

RabbitMQSend.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
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Text;
 
namespace Common.Tool.RabbitMQ
{
    public  class RabbitMQSend
    {
        /// <summary>
        /// Newtonsoft.Json利用IsoDateTimeConverter处理日期类型
        /// </summary>
        static IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
        static RabbitMQConnect connection=null;
 
        static RabbitMQSend()
        {
            connection = new RabbitMQConnect();
        }
 
        /// <summary>
        /// 添加信息到队列
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item">信息</param>
        /// <param name="queueName">队列名</param>
        public static void PushMsgToMq<T>(T item, string queueName)
        {
            string msg = JsonConvert.SerializeObject(item, dtConverter);
            using (global::RabbitMQ.Client.IModel channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: queueName,
                    durable: true,
                    exclusive: false,
                    autoDelete: false,
                    arguments: null);
                //Construct a completely empty content header for use with the Basic content class.
                //构造一个完全空的内容标头,以便与Basic内容类一起使用。
                global::RabbitMQ.Client.IBasicProperties properties = channel.CreateBasicProperties();
                properties.Persistent = true;
                byte[] body = Encoding.UTF8.GetBytes(msg);
                channel.BasicPublish(exchange: "",
                    routingKey: queueName,
                    basicProperties: properties,
                    body: body);
            }
        }
    }
}

  

RabbitMQReceive.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
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
 
namespace Common.Tool.RabbitMQ
{
    public class RabbitMQReceive : IDisposable
    {
        IConnection connection = null;
        IModel channel = null;
 
        public void BindReceiveMqMsg<T>(Func<T, bool> func, Action<string> log, string queueName)
        {
            this.connection = RabbitMQConnect._connectionFactory.CreateConnection();//创建与指定端点的连接。
            this.channel = this.connection.CreateModel(); //创建并返回新的频道,会话和模型。
            this.channel.QueueDeclare(queue: queueName,//队列名称
                             durable: true,//是否持久化, 队列的声明默认是存放到内存中的,如果rabbitmq重启会丢失,如果想重启之后还存在就要使队列持久化,保存到Erlang自带的Mnesia数据库中,当rabbitmq重启之后会读取该数据库
                             exclusive: false,//是否排外的,有两个作用,一:当连接关闭时connection.close()该队列是否会自动删除;二:该队列是否是私有的private,如果不是排外的,可以使用两个消费者都访问同一个队列,没有任何问题,如果是排外的,会对当前队列加锁,其他通道channel是不能访问的,如果强制访问会报异常:com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=405, reply-text=RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'queue_name' in vhost '/', class-id=50, method-id=20)一般等于true的话用于一个队列只能有一个消费者来消费的场景
                             autoDelete: false,//是否自动删除,当最后一个消费者断开连接之后队列是否自动被删除,可以通过RabbitMQ Management,查看某个队列的消费者数量,当consumers = 0时队列就会自动删除
                             arguments: null);//队列中的消息什么时候会自动被删除?
 
            this.channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);//(Spec方法)配置Basic内容类的QoS参数。
                                                                                    //第一个参数是可接收消息的大小的  0不受限制
                                                                                    //第二个参数是处理消息最大的数量  1 那如果接收一个消息,但是没有应答,则客户端不会收到下一个消息,消息只会在队列中阻塞
                                                                                    //第三个参数则设置了是不是针对整个Connection的,因为一个Connection可以有多个Channel,如果是false则说明只是针对于这个Channel的。
            EventingBasicConsumer consumer = new EventingBasicConsumer(this.channel);//构造函数,它将Model属性设置为给定值。
            consumer.Received += (model, bdea) =>
            {
                byte[] body = bdea.Body;
                string message = Encoding.UTF8.GetString(body);
                log?.Invoke(message);
 
                T item = JsonConvert.DeserializeObject<T>(message);
                bool result = func(item);
                if (result)
                {
                    //(Spec方法)确认一个或多个已传送的消息。
                    this.channel.BasicAck(deliveryTag: bdea.DeliveryTag, multiple: false);
                }
            };
            this.channel.BasicConsume(queue: queueName, noAck: false, consumer: consumer); //The consumer is started with noAck = false(i.e.BasicAck is required), an empty consumer tag (i.e. the server creates and returns a fresh consumer tag), noLocal=false and exclusive=false.
        }
        public void Dispose()
        {
            if (this.channel != null)
            {
                this.channel.Close();
            }
 
            if (this.connection != null)
            {
                this.connection.Close();
            }
        }
    }
}

  

RabbitMQ c#版实现(转)的更多相关文章

  1. SpringBoot RabbitMQ 注解版 基本概念与基本案例

    前言 人间清醒 目录 前言 Windows安装RabbitMQ 环境工具下载 Erlang环境安装 RabbitMQ安装 RabbitMQ Web管理端安裝 RabbitMQ新增超级管理员 Rabbi ...

  2. RabbitMQ小结

    1.帮助文档 rabbitmq官网:http://www.rabbitmq.com/ rabbitmq谷歌论坛:https://groups.google.com/forum/#!forum/rabb ...

  3. RabbitMQ 入门【精+转】

    rabbitmq可以用一本书取讲,这里只是介绍一些使用过程中,常用到的基本的知识点.官方文档覆盖的内容,非常全面:http://www.rabbitmq.com/documentation.html  ...

  4. 01.RabbitMQ简单使用

    官网地址:https://www.rabbitmq.com/getstarted.html RabbitMQ 优点: 数据处理异步执行: 应用之间解耦: 流量削峰 1.docker 安装 Rabbit ...

  5. SpringCloud系列之分布式配置中心极速入门与实践

    SpringCloud系列之分布式配置中心极速入门与实践 @ 目录 1.分布式配置中心简介 2.什么是SpringCloud Config? 3.例子实验环境准备 4.Config Server代码实 ...

  6. [译]RabbitMQ教程C#版 - “Hello World”

    [译]RabbitMQ教程C#版 - “Hello World”   先决条件本教程假定RabbitMQ已经安装,并运行在localhost标准端口(5672).如果你使用不同的主机.端口或证书,则需 ...

  7. (五)RabbitMQ消息队列-安装amqp扩展并订阅/发布Demo(PHP版)

    原文:(五)RabbitMQ消息队列-安装amqp扩展并订阅/发布Demo(PHP版) 本文将介绍在PHP中如何使用RabbitMQ来实现消息的订阅和发布.我使用的系统依然是Centos7,为了方便, ...

  8. (六)RabbitMQ消息队列-消息任务分发与消息ACK确认机制(PHP版)

    原文:(六)RabbitMQ消息队列-消息任务分发与消息ACK确认机制(PHP版) 在前面一章介绍了在PHP中如何使用RabbitMQ,至此入门的的部分就完成了,我们内心中一定还有很多疑问:如果多个消 ...

  9. rabbitMQ安装docker版 /权限管理命令

    1.进入docker hub镜像仓库地址:https://hub.docker.com/ 2.搜素rabbitMQ 查询镜像,可以看到多种类型,选择带有web页面的(managment) 3.拉取镜像 ...

随机推荐

  1. Disruptor并发框架简介

    Martin Fowler在自己网站上写一篇LMAX架构的文章,在文章中他介绍了LMAX是一种新型零售金额交易平台,它能够以很低的延迟产生大量交易.这个系统是建立在JVM平台上,其核心是一个业务逻辑处 ...

  2. Delphi: TLabel设置EllipsisPosition属性用...显示过长文本时,以Hint显示其全文本

    仍然是处理多语言中碰到问题. Delphi自2006版以后,TLabel有了EllipsisPosition属性,当长文本超过其大小时,显示以...,如下图: 这样虽然解决显示问题,但很显然,不知道. ...

  3. c#发送短信

    短息计费平台:http://sms.webchinese.cn/User/?action=key 代码: using System;using System.Collections.Generic;u ...

  4. python 数据类型 之 集合

    集合是一个数学概念:由一个或多个确定的元素所构成的整体叫做集合 集合的三个特性: 1.确定性 (element必须可hash,不可变类型是可hash的) 2.互异性(集合中element 不能重复) ...

  5. c# 使用ssh.net 上传文件

    在ssh.net 客户端实例下无法普通用户切换到su root  超级用户,原因是tty 的不支持,具体原因未查, 连接时用超级用户,问题解决 使用ssh.net  能实现远程命令,  使用其中的sf ...

  6. js Map和Set

    Map Map是一组键值对的结构,具有极快的查找速度.JavaScript的对象有个小问题,就是键必须是字符串.但实际上Number或者其他数据类型作为键也是非常合理的.为了解决这个问题,最新的ES6 ...

  7. hdu 1059 (多重背包) Dividing

    这里;http://acm.hdu.edu.cn/showproblem.php?pid=1059 题意是有价值分别为1,2,3,4,5,6的商品各若干个,给出每种商品的数量,问是否能够分成价值相等的 ...

  8. Tech 2 doesn’t system for H2 above 2007

    I purchased my Tech2 from obd2tool.com and it operates excellent. Can not definitely compare softwar ...

  9. POJ3678 Katu Puzzle

    原题链接 \(2-SAT\)模板题. 将\(AND,OR,XOR\)转换成\(2-SAT\)的命题形式连边,用\(tarjan\)求强连通分量并检验即可. #include<cstdio> ...

  10. 在linux虚拟机上安装Docker

    1.简介Docker是一个开源的应用容器引擎:是一个轻量级容器技术: Docker支持将软件编译成一个镜像:然后在镜像中各种软件做好配置,将镜像发布出去,其他使用者可以直接使用这个镜像: 运行中的这个 ...