1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| <?PHP namespace services\rabbitmq; use PHPAmqpLib\Connection\AMQPStreamConnection; use PHPAmqpLib\Exception\AMQPIOException; use PHPAmqpLib\Exchange\AMQPExchangeType; use PHPAmqpLib\Message\AMQPMessage;
class Producer { private $host; private $port; private $user; private $pwd; private $vhost; private static $client; private static $instance; private function __construct($host,$port,$user,$pwd,$vhost) { if (empty($host) || empty($port) || empty($user) || empty($pwd) || empty($vhost)){ $info = config('config')['RabbitMQ']; $this->host = $info['address']; $this->port = $info['port']; $this->user = $info['user']; $this->pwd = $info['pwd']; $this->vhost = $info['vhost']; }else{ $this->host = $host; $this->port = $port; $this->user = $user; $this->pwd = $pwd; $this->vhost = $vhost; } self::$client = new AMQPStreamConnection($this->host, $this->port, $this->user, $this->pwd, $this->vhost); }
public static function getInstance($host = '',$port = '',$user = '',$pwd = '',$vhost = '') { if (!(self::$instance instanceof self)) { self::$instance = new self($host,$port,$user,$pwd,$vhost); } return self::$instance; } public function publishMsg($exchange,$QueueArr,$msg,$message_id,$route_key = '',$expiration = 3600 * 90){ $channel = self::$client->channel();
$channel->exchange_declare($exchange, AMQPExchangeType::DIRECT, false, true, false, false, false, [], null); foreach ($QueueArr as $key=>$value){
$channel->queue_declare($value,false,true,false,false,false); $channel->queue_bind($value, $exchange,$route_key); } $message = new AMQPMessage($msg,array('content_type' => 'text/plain', 'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT,'expiration'=>$expiration * 1000,'message_id'=>$message_id)); $channel->basic_publish($message,$exchange,$route_key); $channel->close(); self::$client->close(); return true; } }
|