1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace PhpCache\CacheServer; |
4
|
|
|
|
5
|
|
|
use PhpCache\IO\CacheIOHandler; |
6
|
|
|
use PhpCache\Storage\Bucket; |
7
|
|
|
use PhpCache\Storage\Maintainer; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Description of CacheServer. |
11
|
|
|
* |
12
|
|
|
* @author dude920228 |
13
|
|
|
*/ |
14
|
|
|
class CacheServer implements CacheServerInterface |
15
|
|
|
{ |
16
|
|
|
private $socket; |
17
|
|
|
private $running; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var CacheIOHandler |
21
|
|
|
*/ |
22
|
|
|
private $ioHandler; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var Bucket |
26
|
|
|
*/ |
27
|
|
|
private $bucket; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var ActionHandler |
31
|
|
|
*/ |
32
|
|
|
private $actionHandler; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var Maintainer |
36
|
|
|
*/ |
37
|
|
|
private $maintainer; |
38
|
|
|
|
39
|
|
|
private $cacheEventListener; |
40
|
|
|
|
41
|
|
|
private $clients; |
42
|
|
|
|
43
|
|
|
public function __construct( |
44
|
|
|
$ioHandler, $bucket, $actionHandler, $maintainer, $cacheEventListener = false |
45
|
|
|
) { |
46
|
|
|
$this->running = true; |
47
|
|
|
$this->ioHandler = $ioHandler; |
48
|
|
|
$this->bucket = $bucket; |
49
|
|
|
$this->actionHandler = $actionHandler; |
50
|
|
|
$this->maintainer = $maintainer; |
51
|
|
|
$this->clients = []; |
52
|
|
|
$this->cacheEventListener = $cacheEventListener; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function run() |
56
|
|
|
{ |
57
|
|
|
$this->socket = $this->ioHandler->createServerSocket(); |
58
|
|
|
while ($this->running) { |
59
|
|
|
$this->maintainer->checkBackup(time(), $this->bucket); |
60
|
|
|
$this->maintainer->maintainBucket($this->bucket); |
61
|
|
|
if (($connection = @socket_accept($this->socket))) { |
62
|
|
|
$clientId = uniqid(); |
63
|
|
|
socket_set_nonblock($connection); |
64
|
|
|
$this->clients[$clientId] = $connection; |
65
|
|
|
$read = $this->clients; |
66
|
|
|
$write = []; |
67
|
|
|
$except = []; |
68
|
|
|
socket_select($read, $write, $except, 10); |
69
|
|
|
$dataString = $this->ioHandler->readFromSocket($connection); |
70
|
|
|
$data = unserialize($dataString); |
71
|
|
|
($this->actionHandler)($data, $this->bucket, $this->ioHandler, $connection, $this); |
72
|
|
|
$this->ioHandler->closeSocket($connection); |
73
|
|
|
unset($this->clients[$clientId]); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function beforeServiceStop() |
79
|
|
|
{ |
80
|
|
|
$this->close(); |
81
|
|
|
$this->maintainer->backup($this->bucket); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
public function close() |
85
|
|
|
{ |
86
|
|
|
$this->ioHandler->closeSocket($this->socket); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
public function getCacheEventListener() |
90
|
|
|
{ |
91
|
|
|
return $this->cacheEventListener; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|