1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TreeHouse\Queue\Processor\Retry; |
4
|
|
|
|
5
|
|
|
use TreeHouse\Queue\Amqp\EnvelopeInterface; |
6
|
|
|
use TreeHouse\Queue\Message\Message; |
7
|
|
|
use TreeHouse\Queue\Message\Publisher\MessagePublisherInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Retries a message, but with an increasing delay for every attempt. |
11
|
|
|
*/ |
12
|
|
|
class BackoffStrategy extends AbstractStrategy |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var MessagePublisherInterface |
16
|
|
|
*/ |
17
|
|
|
protected $publisher; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var int |
21
|
|
|
*/ |
22
|
|
|
protected $cooldownTime; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param MessagePublisherInterface $publisher |
26
|
|
|
* @param int $cooldownTime |
27
|
|
|
*/ |
28
|
1 |
|
public function __construct(MessagePublisherInterface $publisher, $cooldownTime = 600) |
29
|
|
|
{ |
30
|
1 |
|
$this->publisher = $publisher; |
31
|
1 |
|
$this->cooldownTime = $cooldownTime; |
32
|
1 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param int $cooldownTime |
36
|
|
|
*/ |
37
|
|
|
public function setCooldownTime($cooldownTime) |
38
|
|
|
{ |
39
|
|
|
$this->cooldownTime = $cooldownTime; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @return int |
44
|
|
|
*/ |
45
|
|
|
public function getCooldownTime() |
46
|
|
|
{ |
47
|
|
|
return $this->cooldownTime; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @inheritdoc |
52
|
|
|
*/ |
53
|
1 |
|
public function retry(EnvelopeInterface $envelope, $attempt, \Exception $exception = null) |
54
|
|
|
{ |
55
|
1 |
|
$message = $this->createRetryMessage($envelope, $attempt, $exception); |
56
|
|
|
|
57
|
|
|
// multiply cooldown time by the attempt number, |
58
|
1 |
|
$cooldownTime = $attempt * $this->cooldownTime; |
59
|
1 |
|
$cooldownDate = \DateTime::createFromFormat('U', (time() + $cooldownTime)); |
60
|
|
|
|
61
|
1 |
|
return $this->publisher->publish($message, $cooldownDate); |
|
|
|
|
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
This check looks for type mismatches where the missing type is
false
. This is usually indicative of an error condtion.Consider the follow example
This function either returns a new
DateTime
object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returnedfalse
before passing on the value to another function or method that may not be able to handle afalse
.