-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswooleServer.php
105 lines (89 loc) · 2.61 KB
/
swooleServer.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
<?php
class swooleServer
{
public $redis;
public $masterPid = 0;
public $startTime = 0;
public $masterPipe = 0;
public $new_index = 0;
public $works = [];
public function __construct(){
$redis = new Redis();
$redis->connect('127.0.0.1','6379');
$redis->auth('6da192c7dd56a5ba917c59d2e723911a');
$this->redis = $redis;
try {
swoole_set_process_name(sprintf('php-ps:%s', 'master process ('.(__FILE__).')'));
$this->masterPid = posix_getpid();
$this->run();
$this->processWait();
}catch (\Exception $e){
die('ALL ERROR: '.$e->getMessage());
}
}
public function run(){
for($n=0;$n<3;$n++)
{
$this->createProcess($n);
}
}
public function createProcess($n){
$manageProcess = new swoole_process(function(swoole_process $process)use($n){
$process->name(sprintf('php-ps:%s', 'child process '.$n));
$this->handleData($n);
echo "ID:$process->pid --> Process data Fninsh........\n";
$this->checkMpid($process);
});
$managePid = $manageProcess->start();
$this->works[$n] = $managePid;
}
public function handleDataPush($n){
$counter = 0;
while (True){
$this->redis->lPush('num-'.$n,1);
if ($counter==20000){
break;
}
$counter++;
}
}
public function handleData($n){
$counter = 0;
while (True){
$res = $this->redis->lPop('num-'.$n);
if (!$res){
break;
}
//模拟业务逻辑处理所需时间
// $a = [];
// for ($g=1;$g<100000;$g++){
// $a[] = $g;
// }
$this->redis->lPush('num-res',$res);
if ($counter==20000){
break;
}
$counter++;
}
}
public function checkMpid(swoole_process $worker){
if (!swoole_process::kill($this->masterPid,0)){
$worker->exit();
}
}
public function rebootProcess($pid){
$index = array_search($pid, $this->works);
if($index!==false){
$index = intval($index);
$new_pid = $this->createProcess($index);
echo "rebootProcess: {$index}={$new_pid} Done\n";
return;
}
}
public function processWait(){
while ($ret = swoole_process::wait()){
$this->rebootProcess($ret['pid']);
}
}
}
$server = new SwooleServer();