一、安装rabbitMQ、erlang
1.安装rabbitMQ、erlang下载地址
rabbitMQ安装程序下载路径:Installing on Windows | RabbitMQ
erlang环境安装程序下载路径:Downloads - Erlang/OTP
2.配置erlang
环境变量中PATH中编辑添加erlang安装路径。如下图:
3.打开浏览器,访问
服务器公网ip:15672
账号密码默认是guest
二、C#连接 RabbitMQ
/// <summary> /// 获取rabbitmq信道 /// </summary> /// <returns></returns> public static IConnection GetChannel() { //实例连接工厂 ConnectionFactory factory = new ConnectionFactory(); factory.HostName = HostName;//端口 15672 factory.Port = Convert.ToInt16(Port); factory.UserName = UserName;//账号 factory.Password = Password;//密码 factory.VirtualHost = VirtualHost; factory.Protocol = Protocols.DefaultProtocol; IConnection connection = factory.CreateConnection(); return connection; }
三、发送消息
exchange 定义交换机
queue 定义队列
private readonly static string exchange= "exchange_to_cs"; //定义交换机 private readonly static string queue= "queue_to_cs"; //定义队列 /// <summary> /// 发布消息到MQ /// </summary> /// <param name="exchange">交换机</param> /// <param name="queue">队列</param> /// <param name="message">消息主体</param> /// <param name="error">失败返回错误内容</param> /// <returns>true成功,false失败</returns> public static bool PublishMessage(string exchange, string queue, string message, out string error) { try { error = string.Empty; //1.获取信道 using (IConnection connction = RabbitMqUtils.GetChannel()) { using (var channel = connction.CreateModel()) { //声明交换机 channel.ExchangeDeclare(exchange: exchange, type: "topic"); var queueNormalArgs = new Dictionary<string, object>(); { } //声明队列 channel.QueueDeclare(queue: queue, durable: true, exclusive: false, autoDelete: false, arguments: queueNormalArgs); //为队列绑定交换机 channel.QueueBind(queue: queue, exchange: exchange, routingKey: "#"); //开启发布确认 channel.ConfirmSelect(); //编码 var _message = Encoding.UTF8.GetBytes(message); //发布消息 IBasicProperties props = channel.CreateBasicProperties(); props.Persistent = true; //设置消息持久化 channel.BasicPublish(exchange, queue, props, body: _message); bool isok = channel.WaitForConfirms(new TimeSpan(0, 0, 15)); //逐条确认 if (!isok) { error = "rabbitmq服务器异常"; return false; } } } return true; } catch (Exception ex) { error = ex.Message; return false; } }