1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* GpsLab component. |
5
|
|
|
* |
6
|
|
|
* @author Peter Gribanov <[email protected]> |
7
|
|
|
* @copyright Copyright (c) 2011, Peter Gribanov |
8
|
|
|
* @license http://opensource.org/licenses/MIT |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace GpsLab\Domain\Event\Queue\Pull; |
12
|
|
|
|
13
|
|
|
use GpsLab\Domain\Event\Event; |
14
|
|
|
use GpsLab\Domain\Event\Queue\Serializer\Serializer; |
15
|
|
|
use Predis\ClientInterface; |
16
|
|
|
use Psr\Log\LoggerInterface; |
17
|
|
|
|
18
|
|
|
class PredisPullEventQueue implements PullEventQueue |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var ClientInterface |
22
|
|
|
*/ |
23
|
|
|
private $client; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var Serializer |
27
|
|
|
*/ |
28
|
|
|
private $serializer; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var LoggerInterface |
32
|
|
|
*/ |
33
|
|
|
private $logger; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @var string |
37
|
|
|
*/ |
38
|
|
|
private $queue_name = ''; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param ClientInterface $client |
42
|
|
|
* @param Serializer $serializer |
43
|
|
|
* @param LoggerInterface $logger |
44
|
|
|
* @param string $queue_name |
45
|
|
|
*/ |
46
|
3 |
View Code Duplication |
public function __construct(ClientInterface $client, Serializer $serializer, LoggerInterface $logger, $queue_name) |
47
|
|
|
{ |
48
|
3 |
|
$this->client = $client; |
49
|
3 |
|
$this->serializer = $serializer; |
50
|
3 |
|
$this->logger = $logger; |
51
|
3 |
|
$this->queue_name = $queue_name; |
52
|
3 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Publish event to queue. |
56
|
|
|
* |
57
|
|
|
* @param Event $event |
58
|
|
|
* |
59
|
|
|
* @return bool |
60
|
|
|
*/ |
61
|
1 |
|
public function publish(Event $event) |
62
|
|
|
{ |
63
|
1 |
|
$value = $this->serializer->serialize($event); |
64
|
|
|
|
65
|
1 |
|
return (bool) $this->client->rpush($this->queue_name, [$value]); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Pop event from queue. Return NULL if queue is empty. |
70
|
|
|
* |
71
|
|
|
* @return Event|null |
72
|
|
|
*/ |
73
|
2 |
|
public function pull() |
74
|
|
|
{ |
75
|
2 |
|
$value = $this->client->lpop($this->queue_name); |
76
|
|
|
|
77
|
2 |
|
if (!$value) { |
78
|
1 |
|
return null; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
try { |
82
|
2 |
|
return $this->serializer->deserialize($value); |
83
|
1 |
|
} catch (\Exception $e) { |
84
|
|
|
// it's a critical error |
85
|
|
|
// it is necessary to react quickly to it |
86
|
1 |
|
$this->logger->critical('Failed denormalize a event in the Redis queue', [$value, $e->getMessage()]); |
87
|
|
|
|
88
|
|
|
// try denormalize in later |
89
|
1 |
|
$this->client->rpush($this->queue_name, [$value]); |
90
|
|
|
|
91
|
1 |
|
return null; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|