1.在VS2013中新建控制台程序,然后添加引用:.NET/C# RabbitMQ client library
- 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实例