public void 务端() { var connection = RabbitMQProducerHelper.GetConnection(); var channel = connection.CreateModel(); //申明队列接收远程调用请求 channel.QueueDeclare(queue: "rpc_queue", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); Console.WriteLine("[*] Waiting for message."); //请求处理逻辑 consumer.Received += (model, ea) => { var message = Encoding.UTF8.GetString(ea.Body); int n = int.Parse(message); Console.WriteLine($"Receive request of Fib({n})"); int result = n; //从请求的参数中获取请求的唯一标识,在消息回传时同样绑定 var properties = ea.BasicProperties; var replyProerties = channel.CreateBasicProperties(); replyProerties.CorrelationId = properties.CorrelationId; //将远程调用结果发送到客户端监听的队列上 channel.BasicPublish(exchange: "", routingKey: properties.ReplyTo, basicProperties: replyProerties, body: Encoding.UTF8.GetBytes(result.ToString())); //手动发回消息确认 channel.BasicAck(ea.DeliveryTag, false); Console.WriteLine($"Return result: Fib({n})= {result}"); }; //启动消费者 channel.BasicConsume(queue: "rpc_queue", autoAck: false, consumer: consumer); }
public void 客户端() { var connection = RabbitMQProducerHelper.GetConnection(); var channel = connection.CreateModel(); //申明唯一guid用来标识此次发送的远程调用请求 var correlationId = Guid.NewGuid().ToString(); //申明需要监听的回调队列 var replyQueue = channel.QueueDeclare().QueueName; var properties = channel.CreateBasicProperties(); properties.ReplyTo = replyQueue; //指定回调队列 properties.CorrelationId = correlationId; //指定消息唯一标识 var body = Encoding.UTF8.GetBytes("123"); //发布消息 channel.BasicPublish(exchange: "", routingKey: "rpc_queue", basicProperties: properties, body: body); Console.WriteLine($"[*] Request fib()"); //创建消费者用于处理消息回调(远程调用返回结果) var callbackConsumer = new EventingBasicConsumer(channel); channel.BasicConsume(queue: replyQueue, autoAck: true, consumer: callbackConsumer); callbackConsumer.Received += (model, ea) => { //仅当消息回调的ID与发送的ID一致时,说明远程调用结果正确返回。 if (ea.BasicProperties.CorrelationId == correlationId) { var responseMsg = $"Get Response: {Encoding.UTF8.GetString(ea.Body)}"; Console.WriteLine($"[x]: {responseMsg}"); } }; }