1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Shippinno\Job\Infrastructure\Ui\Console\Laravel\Command; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManager; |
6
|
|
|
use Illuminate\Console\Command; |
7
|
|
|
use LogicException; |
8
|
|
|
use Psr\Log\LoggerAwareTrait; |
9
|
|
|
use Psr\Log\LoggerInterface; |
10
|
|
|
use Shippinno\Job\Application\Messaging\EnqueueStoredJobsService; |
11
|
|
|
use Shippinno\Job\Domain\Model\FailedToEnqueueStoredJobException; |
12
|
|
|
|
13
|
|
|
class JobEnqueue extends Command |
14
|
|
|
{ |
15
|
|
|
use LoggerAwareTrait; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* {@inheritdoc} |
19
|
|
|
*/ |
20
|
|
|
protected $signature = 'job:enqueue'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var EnqueueStoredJobsService |
24
|
|
|
*/ |
25
|
|
|
private $service; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var EntityManager |
29
|
|
|
*/ |
30
|
|
|
private $entityManager; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param EnqueueStoredJobsService $service |
34
|
|
|
* @param EntityManager $entityManager |
35
|
|
|
* @param LoggerInterface $logger |
36
|
|
|
*/ |
37
|
|
|
public function __construct( |
38
|
|
|
EnqueueStoredJobsService $service, |
39
|
|
|
EntityManager $entityManager, |
|
|
|
|
40
|
|
|
LoggerInterface $logger |
41
|
|
|
) { |
42
|
|
|
parent::__construct(); |
43
|
|
|
$this->service = $service; |
44
|
|
|
$this->entityManager = $entityManager; |
45
|
|
|
$this->setLogger($logger); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function handle() |
49
|
|
|
{ |
50
|
|
|
$topic = env('JOB_ENQUEUE_TOPIC'); |
51
|
|
|
if (!$topic) { |
52
|
|
|
throw new LogicException('The env JOB_ENQUEUE_TOPIC is not defined'); |
53
|
|
|
} |
54
|
|
|
while (true) { |
55
|
|
|
$this->entityManager->clear(); |
56
|
|
|
try { |
57
|
|
|
$enqueuedMessagesCount = $this->service->execute($topic); |
58
|
|
|
if ($enqueuedMessagesCount > 0) { |
59
|
|
|
$this->logger->debug($enqueuedMessagesCount.' jobs enqueued.'); |
60
|
|
|
$this->entityManager->flush(); |
61
|
|
|
} |
62
|
|
|
} catch (FailedToEnqueueStoredJobException $e) { |
63
|
|
|
$this->logger->alert('Failed to enqueue stored job, retrying in 60 seconds.', [ |
64
|
|
|
'exception' => $e, |
65
|
|
|
]); |
66
|
|
|
sleep(60); |
67
|
|
|
continue; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
The
EntityManager
might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManager
is closed. Any other code which depends on the same instance of theEntityManager
during this request will fail.On the other hand, if you instead inject the
ManagerRegistry
, thegetManager()
method guarantees that you will always get a usable manager instance.