소스 검색

rabbitmq command test

shishao-home 6 년 전
부모
커밋
49f53b124c

+ 2 - 1
common/components/rabbitmq/ImportDataConsumer.php → common/components/rabbitmq/consumer/ImportDataConsumer.php

@@ -6,7 +6,7 @@
  * Time: 14:54
  */
 
-namespace common\components\rabbitmq;
+namespace common\components\rabbitmq\consumer;
 
 use mikemadisonweb\rabbitmq\components\ConsumerInterface;
 use PhpAmqpLib\Message\AMQPMessage;
@@ -21,6 +21,7 @@ class ImportDataConsumer implements ConsumerInterface
 	{
 		$data = unserialize($msg->body);
 		print_r($data);
+        print_r('ImportDataConsumer done! ');
 
 		//有什么东西可以放到队列里去
 		//微信模板消息

+ 34 - 0
common/components/rabbitmq/consumer/PrintMsgConsumer.php

@@ -0,0 +1,34 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: shish <shish@zhhinc.com>
+ * Date: 2019/9/9 0009
+ * Time: 14:54
+ */
+
+namespace common\components\rabbitmq\consumer;
+
+use mikemadisonweb\rabbitmq\components\ConsumerInterface;
+use PhpAmqpLib\Message\AMQPMessage;
+
+class PrintMsgConsumer implements ConsumerInterface
+{
+	/**
+	 * @param AMQPMessage $msg
+	 * @return bool
+	 */
+	public function execute(AMQPMessage $msg)
+	{
+		$data = unserialize($msg->body);
+		print_r($data);
+        print_r('PrintMsgConsumer done! ');
+
+		return ConsumerInterface::MSG_ACK;
+		/**
+         * ConsumerInterface::MSG_ACK - Acknowledge message (mark as processed) and drop it from the queue
+         * ConsumerInterface::MSG_REJECT - Reject and drop message from the queue
+         * ConsumerInterface::MSG_REJECT_REQUEUE - Reject and requeue message in RabbitMQ
+         */
+	}
+
+}

+ 1 - 48
common/config/main.php

@@ -38,54 +38,6 @@ return [
 		'dict' => [
 			'class' => 'common\components\configDict',
 		],
-		'rabbitmq' => [
-			'class' => 'mikemadisonweb\rabbitmq\Configuration',
-			'connections' => [
-				[
-					'host' => '127.0.0.1',
-					'port' => '5672',
-					'user' => 'admin',
-					'password' => 'vn3oaz1i8w32k4mm9',
-					'vhost' => '/',
-				]
-			],
-			'exchanges' => [
-				[
-					'name' => 'ex1',
-					'type' => 'direct'
-				],
-			],
-			'queues' => [
-				[
-					'name' => 'queues1',
-					'passive' => false,
-				],
-				[
-					'name' => 'queues2',
-					'passive' => false,
-				],
-			],
-			'bindings' => [
-				[
-					'queue' => 'queues1',
-					'exchange' => 'ex1',
-					'routing_keys' => ['route1'],
-				],
-			],
-			'producers' => [
-				[
-					'name' => 'producers',
-				],
-			],
-			'consumers' => [
-				[
-					'name' => 'consumers',
-					'callbacks' => [
-						'queues1' => '\common\components\rabbitmq\ImportDataConsumer',
-					],
-				],
-			],
-		],
 		'mailer' => [
 			'class' => 'yii\swiftmailer\Mailer',
 			'useFileTransport' => false,
@@ -102,5 +54,6 @@ return [
 				'from' => ['zhhinc@126.com' => '系统邮件']
 			],
 		],
+        'rabbitmq' => require(__DIR__ . '/rabbitmq.php'),
 	],
 ];

+ 144 - 0
common/config/rabbitmq.php

@@ -0,0 +1,144 @@
+<?php
+use mikemadisonweb\rabbitmq\Configuration;
+/**
+ * rabbitmq的配置
+ */
+
+$rabbitmq = [
+    /*'on before_consume' => function ($event) {
+        if (isset(\Yii::$app->db)) {
+            $db = \Yii::$app->db;
+            if ($db->getIsActive()) {
+                $db->close();
+            }
+            $db->open();
+        }
+    },
+    'logger' => [
+        'enable' => true,
+        'category' => 'amqp',
+        'print_console' => true,
+    ],*/
+    'class' => 'mikemadisonweb\rabbitmq\Configuration',
+    'connections' => [
+        [
+            'host' => '127.0.0.1',
+            'port' => '5672',
+            'user' => 'guest',
+            'password' => 'guest',
+            'vhost' => '/', //虚拟主机
+        ]
+    ],
+
+    /**
+     * 交换器
+     * 交换类型(type):direct、topic、headers、fanout
+     * 列出交换器: rabbitmqctl list_exchanges
+     */
+    'exchanges' => [
+        [
+            'name' => 'ex1',
+            'type' => 'direct'
+        ],
+        [
+            'name' => 'ex2',
+            'type' => 'topic',
+            'passive' => false,
+            'durable' => true,
+            'auto_delete' => false,
+            'internal' => false,
+            'nowait' => false,
+            'arguments' => null,
+            'ticket' => null,
+            'declare' => true,
+        ],
+    ],
+
+    /**
+     * 队列
+     */
+    'queues' => [
+        [
+            'name' => 'queue_1',
+            'passive' => false,
+            // Queue can be configured here the way you want it:
+            //'durable' => true,
+            //'auto_delete' => false,
+        ],
+        [
+            'name' => 'queue_2',
+            'passive' => false,
+            'durable' => true,
+            'exclusive' => false,
+            'auto_delete' => false,
+            'nowait' => false,
+            'arguments' => null,
+            'ticket' => null,
+            'declare' => true,
+        ],
+    ],
+
+    /**
+     * 交换和队列之间的关系称为绑定
+     * 列出绑定: rabbitmqctl list_bindings
+     */
+    'bindings' => [
+        [
+            'queue' => 'queue_1',
+            'exchange' => 'ex1',
+            'routing_keys' => ['route1'],
+        ],
+        [
+            'queue' => 'queue_2',
+            'exchange' => 'ex2',
+            'routing_keys' => ['route1', 'route2'],
+        ],
+    ],
+
+    /**
+     * 生产者
+     */
+    'producers' => [
+        [
+            'name' => 'producer_1',
+        ],
+        [
+            'name' => 'producer_2',
+            'connection' => Configuration::DEFAULT_CONNECTION_NAME,
+            'safe' => true,
+            'content_type' => 'text/plain',
+            'delivery_mode' => 2,
+            'serializer' => 'serialize',
+        ]
+    ],
+
+    /**
+     * 消费者
+     */
+    'consumers' => [
+        [
+            'name' => 'consumer_1',
+            'callbacks' => [
+                'queue_1' => '\common\components\rabbitmq\consumer\ImportDataConsumer', //设定队列的数据给谁转回调而以,只是个配置
+            ],
+        ],
+        [
+            'name' => 'consumer_2',
+            'connection' => Configuration::DEFAULT_CONNECTION_NAME,
+            'callbacks' => [
+                'queue_2' => '\common\components\rabbitmq\consumer\PrintMsgConsumer',
+            ],
+            'qos' => [
+                'prefetch_size' => 0,
+                'prefetch_count' => 0,
+                'global' => false,
+            ],
+            'idle_timeout' => 0,
+            'idle_timeout_exit_code' => null,
+            'proceed_on_exception' => false,
+            'deserializer' => 'unserialize',
+        ],
+    ],
+];
+
+return $rabbitmq;

+ 34 - 0
console/controllers/RabbitmqTestController.php

@@ -0,0 +1,34 @@
+<?php
+
+
+namespace console\controllers;
+
+use yii\console\Controller;
+
+class RabbitmqTestController extends Controller
+{
+    /**
+     * @param $producerName 生产者名称 (producer.name) -- 从 config/rabbitmq.php 找
+     * @param $exchangeName 交换器名称 (exchanges.name)
+     * @param $routingKey 绑定路由键(bindings.routing_keys)
+     */
+    public function actionPublish($producerName = '', $exchangeName = '', $routingKey = '')
+    {
+        if(empty($producerName)){
+            $producerName = 'producer_1';
+        }
+        if(empty($exchangeName)){
+            $exchangeName = 'ex1';
+        }
+        if(empty($routingKey)){
+            $routingKey = 'route1';
+        }
+
+        $producer = \Yii::$app->rabbitmq->getProducer($producerName);
+        $data = ['id' => 123, 'status' => 200, ['producer'=>$producerName, 'exchange'=>$exchangeName, 'routingKey'=>$routingKey]];
+        $msg = serialize($data);
+        $producer->publish($msg, $exchangeName, $routingKey);
+    }
+
+
+}

+ 1 - 0
yii

@@ -22,6 +22,7 @@ $config = yii\helpers\ArrayHelper::merge(
     require(__DIR__ . '/console/config/main-local.php')
 );
 
+unset($config['components']['request']); // 解决执行 yii 命令时的报错 (https://stackoverflow.com/questions/47036901/yii2-console-app-cookievalidationkey-config-errors/47686071)
 $application = new yii\console\Application($config);
 $exitCode = $application->run();
 exit($exitCode);