1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Genkgo\Mail\Queue; |
5
|
|
|
|
6
|
|
|
use Genkgo\Mail\Exception\EmptyQueueException; |
7
|
|
|
use Genkgo\Mail\Exception\QueueStoreException; |
8
|
|
|
use Genkgo\Mail\GenericMessage; |
9
|
|
|
use Genkgo\Mail\MessageInterface; |
10
|
|
|
use Predis\ClientInterface; |
11
|
|
|
use Predis\Connection\ConnectionException; |
12
|
|
|
|
13
|
|
|
final class RedisQueue implements QueueInterface, \Countable |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var ClientInterface |
17
|
|
|
*/ |
18
|
|
|
private $client; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
private $key; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ClientInterface $client |
27
|
|
|
* @param string $key |
28
|
|
|
*/ |
29
|
4 |
|
public function __construct(ClientInterface $client, string $key) |
30
|
|
|
{ |
31
|
4 |
|
$this->client = $client; |
32
|
4 |
|
$this->key = $key; |
33
|
4 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param MessageInterface $message |
37
|
|
|
* @throws QueueStoreException |
38
|
|
|
*/ |
39
|
3 |
|
public function store(MessageInterface $message): void |
40
|
|
|
{ |
41
|
|
|
try { |
42
|
3 |
|
$this->client->rpush($this->key, ...[(string)$message]); |
43
|
|
|
} catch (ConnectionException $e) { |
44
|
|
|
throw new QueueStoreException('Cannot add message to redis queue: ' . $e->getMessage()); |
45
|
|
|
} |
46
|
3 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return MessageInterface |
50
|
|
|
* @throws EmptyQueueException |
51
|
|
|
* @throws QueueStoreException |
52
|
|
|
*/ |
53
|
2 |
|
public function fetch(): MessageInterface |
54
|
|
|
{ |
55
|
|
|
try { |
56
|
2 |
|
$message = $this->client->lpop($this->key); |
57
|
2 |
|
if ($message) { |
58
|
2 |
|
return GenericMessage::fromString($message); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
throw new EmptyQueueException(); |
62
|
1 |
|
} catch (ConnectionException $e) { |
63
|
|
|
throw new QueueStoreException('Cannot add message to redis queue ' . $e->getMessage()); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return int |
69
|
|
|
* @throws QueueStoreException |
70
|
|
|
*/ |
71
|
1 |
|
public function count(): int |
72
|
|
|
{ |
73
|
|
|
try { |
74
|
1 |
|
return $this->client->llen($this->key); |
75
|
|
|
} catch (ConnectionException $e) { |
76
|
|
|
throw new QueueStoreException('Cannot get messages from redis queue ' . $e->getMessage()); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|