1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Initx\Querabilis\Driver; |
4
|
|
|
|
5
|
|
|
use Initx\Querabilis\Envelope; |
6
|
|
|
use Initx\Querabilis\Exception\IllegalStateException; |
7
|
|
|
use Initx\Querabilis\Queue; |
8
|
|
|
use JMS\Serializer\SerializerInterface; |
9
|
|
|
use Predis\ClientInterface; |
10
|
|
|
use Throwable; |
11
|
|
|
|
12
|
|
|
final class RedisQueue implements Queue |
13
|
|
|
{ |
14
|
|
|
use HasFallbackSerializer; |
15
|
|
|
use HasDefaultRemoveAndElement; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var ClientInterface |
19
|
|
|
*/ |
20
|
|
|
private $client; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var SerializerInterface |
24
|
|
|
*/ |
25
|
|
|
private $serializer; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string |
29
|
|
|
*/ |
30
|
|
|
private $queueName; |
31
|
|
|
|
32
|
6 |
|
public function __construct(ClientInterface $client, string $queueName, ?SerializerInterface $serializer = null) |
33
|
|
|
{ |
34
|
6 |
|
$this->client = $client; |
35
|
6 |
|
$this->queueName = $queueName; |
36
|
6 |
|
$this->serializer = $this->fallbackSerializer($serializer); |
37
|
6 |
|
} |
38
|
|
|
|
39
|
5 |
|
public function add(Envelope $envelope): bool |
40
|
|
|
{ |
41
|
5 |
|
if (!$this->offer($envelope)) { |
42
|
|
|
throw new IllegalStateException("Could not write to redis"); |
43
|
|
|
} |
44
|
|
|
|
45
|
5 |
|
return true; |
46
|
|
|
} |
47
|
|
|
|
48
|
6 |
|
public function offer(Envelope $envelope): bool |
49
|
|
|
{ |
50
|
6 |
|
$serialized = $this->serializer->serialize($envelope, 'json'); |
51
|
|
|
|
52
|
6 |
|
return (bool)$this->client->rpush( |
53
|
6 |
|
$this->queueName, |
54
|
6 |
|
[$serialized] |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
public function poll(): ?Envelope |
59
|
|
|
{ |
60
|
|
|
try { |
61
|
2 |
|
$serialized = $this->client->lpop($this->queueName); |
62
|
|
|
} catch (Throwable $e) { |
63
|
|
|
throw new IllegalStateException("Predis connection error", 0, $e); |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
if (empty($serialized)) { |
67
|
1 |
|
return null; |
68
|
|
|
} |
69
|
|
|
|
70
|
2 |
|
return $this->serializer->deserialize($serialized, Envelope::class, 'json'); |
71
|
|
|
} |
72
|
|
|
|
73
|
2 |
|
public function peek(): ?Envelope |
74
|
|
|
{ |
75
|
2 |
|
$serialized = $this->client->lrange($this->queueName, 0, 0)[0]; |
76
|
|
|
|
77
|
2 |
|
if (empty($serialized)) { |
78
|
|
|
return null; |
79
|
|
|
} |
80
|
|
|
|
81
|
2 |
|
return $this->serializer->deserialize($serialized, Envelope::class, 'json'); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|