原文:第四节 RabbitMQ在C#端的应用-客户端连接
版权声明:未经本人同意,不得转载该文章,谢谢 https://blog.csdn.net/phocus1/article/details/87357911 </div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<div class="htmledit_views" id="content_views">
<p><strong>1.在VS2013中新建控制台程序</strong>,然后添加引用:.NET/C# RabbitMQ client library</p>
- RabbitMQ .NET Client (supports .NET Core and .NET 4.5.1+)
使用NuGet程序包下载RabbitMQ.Client,如下所示:
2.在代码中添加引用,并编写连接代码
using RabbitMQ.Client;
//核心代码:
try
{
ConnectionFactory factory = new ConnectionFactory();
factory.UserName = "wiadmin";
factory.Password = "wi2019";
factory.HostName = "127.0.0.1";
factory.VirtualHost = "/";//默认情况可省略此行
factory.Port = 5672;//此处默认即为5672端口,可省略此行
IConnection conn = factory.CreateConnection();
Console.Write("---------------RabbitMQ连接成功---------------
");
}
catch (Exception ex)
{
Console.Write(string.Format("RabbitMQ连接异常:{0}
", ex.ToString()));
}
此时连接会提示错误,如下图:
此时显示wiadmin账户没有相应的权限,现在可通过管理端为其他添加权限,如下:
添加权限前:
添加权限后:
再次运行程序,将不会报错:
补充说明,此处使用到两核心API:
IConnection:表示AMQP 0-9-1连接
ConnectionFactory:构造IConnection实例