forked from micmorozov/yii2-gearman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.php
137 lines (122 loc) · 2.86 KB
/
Worker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
<?php
namespace micmorozov\yii2\gearman;
use Serializable;
use GearmanException;
use GearmanWorker;
use Psr\Log\LoggerInterface;
use micmorozov\yii2\gearman\exception\ServerConnectionException;
class Worker
{
/**
* @var GearmanWorker
*/
private $worker;
/**
* @var Config
*/
private $config;
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var array
*/
private $functions = [];
/**
* @param Config $config
* @param null|LoggerInterface $logger
* @throws ServerConnectionException
*/
public function __construct(Config $config, LoggerInterface $logger = null)
{
$this->setConfig($config);
if (null !== $logger) {
$this->setLogger($logger);
}
}
public function resetWorker()
{
if ($this->worker instanceof GearmanWorker) {
$this->worker->unregisterAll();
}
$this->worker = null;
$this->createWorker();
}
/**
* @throws Exception\ServerConnectionException
*/
private function createWorker()
{
$this->worker = new GearmanWorker();
$servers = $this->getConfig()->getServers();
$exceptions = [];
foreach ($servers as $server) {
try {
$this->worker->addServer($server->getHost(), $server->getPort());
} catch (GearmanException $e) {
$message = 'Unable to connect to Gearman Server ' . $server->getHost() . ':' . $server->getPort();
if (null !== $this->logger) {
$this->logger->info($message);
}
$exceptions[] = $message;
}
}
if (count($exceptions)) {
foreach ($exceptions as $exception) {
throw new ServerConnectionException($exception);
}
}
}
/**
* @return Config
*/
public function getConfig()
{
return $this->config;
}
/**
* @param Config $config
* @return $this
*/
public function setConfig(Config $config)
{
$this->config = $config;
return $this;
}
/**
* @return GearmanWorker
*/
public function getWorker()
{
if (null === $this->worker) {
$this->createWorker();
}
return $this->worker;
}
/**
* @param GearmanWorker $worker
* @return $this
*/
public function setWorker(GearmanWorker $worker)
{
$this->worker = $worker;
return $this;
}
/**
* @return LoggerInterface
*/
public function getLogger()
{
return $this->logger;
}
/**
* @param null|LoggerInterface $logger
* @return $this
*/
public function setLogger(LoggerInterface $logger = null)
{
$this->logger = $logger;
return $this;
}
}