1、问题复现
RabbitMQ的官方示例:RabbitMQ消费端(接收端)获取消息时抛出异常,具体代码如下
var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); // <------错误点 Console.WriteLine(" [x] Received {0}", message); };
2、解决办法
查看定义可以看到Encoding.UTF8.GetString重载的方法有多个,参数为字节数组或其指针或只读的字节跨度。
RabbitMQ更新API的地址:https://github.com/rabbitmq/rabbitmq-dotnet-client/commit/8bf93082fd2c18bbd6adff260d38a6fd34d6840b
接下来说下解决办法
① ToArrary()
示例是之前的示例,现在官方示例已更正,最新示例地址:https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html
var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body.ToArray(); // 将内存区域的内容复制到一个新的数组中 var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); };
② Span
var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body.Span; // 从内存区域获取一个跨度 var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); };