Skip to content

在ZF2中使用RabbitMQ

Published: at 00:00
安装
安装信息加入composer.json

{
	"require": {
    	"videlalvaro/php-amqplib": "v2.1.0"
	}
}

执行命令
php composer.phar install
配置
在config/autoload增加amqp.local.php

<?php
return array(
	'amqp' => array(
    	'host' => '10.211.55.61',
    	'port' => 5672,
    	'user' => 'nate',
    	'password' => '123123',
    	'vhost' => 'test_vhost',
    	'debug' => true,
	),
);
Action代码
public function sendAction() {
    $config = $this->getServiceLocator()->get('config')['amqp'];
    $channel = null;
    $conn = null;
    try {
        $conn = new AMQPConnection($config['host'], $config['port'], $config['user'], $config['password'], $config['vhost']);
        $channel = $conn->channel();

        $exchange = 'logs_2';
        //direct exchange
        $channel->exchange_declare($exchange, 'direct', false, false, false);
        //fanout exchange
        //$channel->exchange_declare($exchange, 'fanout', false, false, false);
        //topic exchange
        //$channel->exchange_declare($exchange, 'topic', false, false, false);

        //direct key
        $key = 'test';
        //topic key
        //$key = 'log.#';
        //$key = 'log.*';

        $content = 'This is Test! at ' . date('Y-m-d');
        $msg = new AMQPMessage($content, array('content_type' => 'text/plain'));
        $channel->basic_publish($msg, $exchange, $key);

        if (! is_null($channel)) {
            $channel->close();
        }

        if (! is_null($conn)) {
            $conn->close();
        }

        echo "sent " . $content;
        exit;

    } catch (AMQPProtocolConnectionException $ex) {
        echo $ex->getMessage();
        exit;
    }

}