forked from kcloze/swoole-jobs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRabbitmq.php
65 lines (57 loc) · 1.93 KB
/
Rabbitmq.php
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
<?php
/*
* This file is part of PHP CS Fixer.
* (c) kcloze <[email protected]>
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Kcloze\Jobs;
class Rabbitmq extends Queue
{
private $connection = null;
private $channel = null;
private $exchange = null;
private $queue = null;
public function __construct(array $config)
{
try {
$class = class_exists('AMQPConnection', false);
if ($class) {
$this->connection = new \AMQPConnection();
$this->connection->setHost($config['host']);
$this->connection->setLogin($config['login']);
$this->connection->setPassword($config['password']);
$this->connection->setVhost($config['vhost']);
$this->connection->connect();
} else {
die('you need install pecl amqp extension');
}
$this->channel = new \AMQPChannel($this->connection);
//AMQPC Exchange is the publishing mechanism
$this->exchange = new \AMQPExchange($this->channel);
$this->queue = new \AMQPQueue($this->channel);
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
}
public function push($key, $value)
{
$this->queue->setName($key);
$this->queue->setFlags(AMQP_DURABLE);
$this->queue->declareQueue();
$result = $this->exchange->publish(serialize($value), $key);
return $result;
}
public function pop($key)
{
$this->queue->setName($key);
$this->queue->setFlags(AMQP_DURABLE);
$this->queue->declareQueue();
$message = $this->queue->get(AMQP_AUTOACK);
$result = null;
if ($message) {
$result = $message->getBody();
}
return $result ? unserialize($result) : null;
}
}