一、文档资料
1、服务端代码
namespace Server
{
class Program
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//定义队列(hello为队列名)
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer);
Console.WriteLine(" [*] Waiting for messages." +
"To exit press CTRL+C");
while (true)
{
//接受客户端发送的消息并打印出来
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
}
}
}
}
}
}
namespace Client
{
class Program
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
//定义队列(hello为队列名)
channel.QueueDeclare("hello", false, false, false, null);
//发送到队列的消息,包含时间戳
string message = "Hello World!" + "_" + DateTime.Now.ToString();
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "hello", null, body);
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
}
}
六、异常问题
1、None of the specified endpoints were reachable
生产端和消费端的factory参数要统一
var factory = new ConnectionFactory();
factory.UserName = QueueSetttiong.UserName; //用户名,对应Management工具的admin-->user
factory.Password = QueueSetttiong.Password; //密码,对应Management工具的admin-->密码
factory.HostName = QueueSetttiong.HostName; //本地部署服务直接用hostname即可
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
factory.VirtualHost = QueueSetttiong.VirtualHost; //使用默认值: "/"
factory.Protocol = Protocols.DefaultProtocol;