【问题标题】:Publish fanout array with RabbitMQ使用 RabbitMQ 发布扇出数组
【发布时间】:2016-07-26 23:08:58
【问题描述】:

如何使用basic_publish 通过扇出发送数组?

我正在这样做:

// $this->message is the array to send
$props = array('content_type' => 'application/json');
$msg = new AMQPMessage($this->message, $props);

$channel->basic_publish($msg, $this->fanoutName);

我得到这个错误:

AMQPChannel.php 第 1098 行中的 ErrorException: mb_strlen() 期望参数 1 是字符串,给定数组

我搜索了很多,但找不到发送数组而不是字符串的方法。

【问题讨论】:

  • $this->message 的例子是什么?它应该如何为给定的数组制定消息?
  • @FirstOne 数组是从另一个函数接收的,数组内容例如:$this->message = array('a' => 'b');
  • 好的。以及应该如何基于数组来制定消息?我的意思是,给定该数组的预期消息是什么? 编辑:请把这些信息放在问题中(这可能会增加你得到答案的几率)
  • 由于参数有点需要字符串,您可以使用implode 或循环给定数组以生成预期的消息。
  • @FirstOne 会是这样的:$this->message = array('id' => 12345, 'status' => 'available', 'content' => 'the content...');

标签: php rabbitmq


【解决方案1】:

使用json_encode将数组转换为JSON

http://www.dyn-web.com/tutorials/php-js/json/array.php


// $this->message is the array to send
$props = array('content_type' => 'application/json');

// convert the array to json
$data = json_encode($this->message);

// send the resulting json data
$msg = new AMQPMessage($data, $props);

$channel->basic_publish($msg, $this->fanoutName);

【讨论】:

  • 这不是解决方案。