PHP code example of apptension / yii2-rabbitmq
1. Go to this page and download the library: Download apptension/yii2-rabbitmq library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
apptension / yii2-rabbitmq example snippets
// config/main.php
return [
// ...
'components' => [
// ...
'rabbitmq' => [
'class' => 'mikemadisonweb\rabbitmq\Configuration',
'connections' => [
'default' => [
'host' => '127.0.0.1',
'port' => '5672',
'user' => 'your_username',
'password' => 'your_password',
'vhost' => '/',
'heartbeat' => 0,
],
],
'producers' => [
'import_data' => [
'connection' => 'default',
'exchange_options' => [
'name' => 'import_data',
'type' => 'direct',
],
],
],
'consumers' => [
'import_data' => [
'connection' => 'default',
'exchange_options' => [
'name' => 'import_data',
'type' => 'direct',
],
'queue_options' => [
'name' => 'import_data',
],
'callback' => \path\to\ImportDataConsumer::class,
],
],
],
// ...
],
// ...
'controllerMap' => [
'rabbitmq-consumer' => \mikemadisonweb\rabbitmq\controllers\ConsumerController::className(),
'rabbitmq-producer' => \mikemadisonweb\rabbitmq\controllers\ProducerController::className(),
],
// ...
];
// config/main.php
return [
// ...
'components' => [
// ...
'rabbitmq' => [
// ...
'multipleConsumers' => [
'import_data' => [
'connection' => 'default',
'exchange_options' => [
'name' => 'exchange_name',
'type' => 'direct',
],
'queues' => [
'import_data' => [
'name' => 'import_data',
'callback' => \path\to\ImportDataConsumer::class,
'routing_keys' => ['import_data'],
],
'update_index' => [
'name' => 'update_index',
'callback' => \path\to\UpdateIndexConsumer::class,
'routing_keys' => ['update_index'],
],
],
],
],
],
// ...
],
];
// config/main.php
return [
// ...
'components' => [
// ...
'rabbitmq' => [
// ...
'on before_consume' => function ($event) {
if (isset(\Yii::$app->db)) {
if (\Yii::$app->db->getIsActive()) {
\Yii::$app->db->close();
}
\Yii::$app->db->open();
}
},
],
// ...
],
];
// config/main.php
return [
// ...
'components' => [
// ...
'rabbitmq' => [
// ...
'logger' => [
'enable' => true,
'category' => 'amqp',
'print_console' => true,
],
],
// ...
],
];
namespace components\rabbitmq;
use mikemadisonweb\rabbitmq\components\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
class ImportDataConsumer implements ConsumerInterface
{
/**
* @param AMQPMessage $msg
* @return bool
*/
public function execute(AMQPMessage $msg)
{
$data = unserialize($msg->body);
if ($this->isValid($data)) {
// Apply your business logic here
return ConsumerInterface::MSG_ACK;
}
}
}
\Yii::$app->rabbitmq->load();
$producer = \Yii::$container->get(sprintf('rabbit_mq.producer.%s', 'exchange_name'));
$msg = serialize(['dataset_id' => $dataset->id, 'linked_datasets' => []]);
$producer->publish($msg, 'import_data');