swoole_process實現進程池的方法示例


swoole —— 重新定義PHP

swoole 的進程之間有兩種通信方式,一種是消息隊列(queue),另一種是管道(pipe),對swoole_process 的研究在swoole中顯得尤為重要。

預備知識

IO多路復用

swoole 中的io多路復用表現為底層的 epoll進程模型,在C語言中表現為 epoll 函數。

  • epoll 模型下會持續監聽自己名下的素有socket 描述符 fd
  • 當觸發了 socket 監聽的事件時,epoll 函數才會響應,並返回所有監聽該時間的 socket 集合
  • epoll 的本質是阻塞IO,它的優點在於能同事處理大量socket連接

Event loop 事件循環

swoole 對 epoll 實現了一個Reactor線程模型封裝,設置了read事件和write事件的監聽回調函數。(詳見swoole_event_add)

  • Event loop 是一個Reactor線程,其中運行了一個epoll實例。
  • 通過swoole_event_add將socket描述符的一個事件添加到epoll監聽中,事件發生時將執行回調函數
  • 不可用於fpm環境下,因為fpm在任務結束時可能會關掉進程。

swoole_process

  • 基於C語言封裝的進程管理模塊,方便php來調用
  • 內置管道、消息隊列接口,方便實現進程間通信

我們在php-fpm.conf配置文件中發現,php-fpm中有兩種進程池管理設置。

  • 靜態模式 即初始化固定的進程數,當來了一個請求時,從中選取一個進程來處理。
  • 動態模式 指定最小、最大進程數,當請求量過大,進程數不超過最大限制時,新增線程去處理請求

接下來用swoole代碼來實現,這里只是為理解swoole_process、進程間通信、定時器等使用,實際情況使用封裝好的swoole_server來實現task任務隊列池會更方便。

假如有個定時投遞的任務隊列:

?
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<?php
 
/**
  * 動態進程池,類似fpm
  * 動態新建進程
  * 有初始進程數,最小進程數,進程不夠處理時候新建進程,不超過最大進程數
  */
 
// 一個進程定時投遞任務
 
/**
  * 1. tick
  * 2. process及其管道通訊
  * 3. event loop 事件循環
  */
class processPool
{
   private $pool ;
 
   /**
    * @var swoole_process[] 記錄所有worker的process對象
    */
   private $workers = [];
 
   /**
    * @var array 記錄worker工作狀態
    */
   private $used_workers = [];
 
   /**
    * @var int 最小進程數
    */
   private $min_woker_num = 5;
 
   /**
    * @var int 初始進程數
    */
   private $start_worker_num = 10;
 
   /**
    * @var int 最大進程數
    */
   private $max_woker_num = 20;
 
   /**
    * 進程閑置銷毀秒數
    * @var int
    */
   private $idle_seconds = 5;
 
   /**
    * @var int 當前進程數
    */
   private $curr_num ;
 
   /**
    * 閑置進程時間戳
    * @var array
    */
   private $active_time = [];
 
   public function __construct()
   {
     $this ->pool = new swoole_process( function () {
       // 循環建立worker進程
       for ( $i = 0; $i < $this ->start_worker_num; $i ++) {
         $this ->createWorker();
       }
       echo '初始化進程數:' . $this ->curr_num . PHP_EOL;
       // 每秒定時往閑置的worker的管道中投遞任務
       swoole_timer_tick(1000, function ( $timer_id ) {
         static $count = 0;
         $count ++;
         $need_create = true;
         foreach ( $this ->used_workers as $pid => $used ) {
           if ( $used == 0) {
             $need_create = false;
             $this ->workers[ $pid ]->write( $count . ' job' );
             // 標記使用中
             $this ->used_workers[ $pid ] = 1;
             $this ->active_time[ $pid ] = time();
             break ;
           }
         }
         foreach ( $this ->used_workers as $pid => $used )
           // 如果所有worker隊列都沒有閑置的,則新建一個worker來處理
           if ( $need_create && $this ->curr_num < $this ->max_woker_num) {
             $new_pid = $this ->createWorker();
             $this ->workers[ $new_pid ]->write( $count . ' job' );
             $this ->used_workers[ $new_pid ] = 1;
             $this ->active_time[ $new_pid ] = time();
           }
 
         // 閑置超過一段時間則銷毀進程
         foreach ( $this ->active_time as $pid => $timestamp ) {
           if ((time() - $timestamp ) > $this ->idle_seconds && $this ->curr_num > $this ->min_woker_num) {
             // 銷毀該進程
             if (isset( $this ->workers[ $pid ]) && $this ->workers[ $pid ] instanceof swoole_process) {
               $this ->workers[ $pid ]->write( 'exit' );
               unset( $this ->workers[ $pid ]);
               $this ->curr_num = count ( $this ->workers);
               unset( $this ->used_workers[ $pid ]);
               unset( $this ->active_time[ $pid ]);
               echo "{$pid} destroyed\n" ;
               break ;
             }
           }
         }
 
         echo "任務{$count}/{$this->curr_num}\n" ;
 
         if ( $count == 20) {
           foreach ( $this ->workers as $pid => $worker ) {
             $worker ->write( 'exit' );
           }
           // 關閉定時器
           swoole_timer_clear( $timer_id );
           // 退出進程池
           $this ->pool-> exit (0);
           exit ();
         }
       });
 
     });
 
     $master_pid = $this ->pool->start();
     echo "Master $master_pid start\n" ;
 
     while ( $ret = swoole_process::wait()) {
       $pid = $ret [ 'pid' ];
       echo "process {$pid} existed\n" ;
     }
   }
 
   /**
    * 創建一個新進程
    * @return int 新進程的pid
    */
   public function createWorker()
   {
     $worker_process = new swoole_process( function (swoole_process $worker ) {
       // 給子進程管道綁定事件
       swoole_event_add( $worker ->pipe, function ( $pipe ) use ( $worker ) {
         $data = trim( $worker ->read());
         if ( $data == 'exit' ) {
           $worker -> exit (0);
           exit ();
         }
         echo "{$worker->pid} 正在處理 {$data}\n" ;
         sleep(5);
         // 返回結果,表示空閑
         $worker ->write( "complete" );
       });
     });
 
     $worker_pid = $worker_process ->start();
 
     // 給父進程管道綁定事件
     swoole_event_add( $worker_process ->pipe, function ( $pipe ) use ( $worker_process ) {
       $data = trim( $worker_process ->read());
       if ( $data == 'complete' ) {
         // 標記為空閑
//        echo "{$worker_process->pid} 空閑了\n";
         $this ->used_workers[ $worker_process ->pid] = 0;
       }
     });
 
     // 保存process對象
     $this ->workers[ $worker_pid ] = $worker_process ;
     // 標記為空閑
     $this ->used_workers[ $worker_pid ] = 0;
     $this ->active_time[ $worker_pid ] = time();
     $this ->curr_num = count ( $this ->workers);
     return $worker_pid ;
   }
 
}
 
new processPool();

 

 

 
安全中國PHP網站開發工程師就業指導班
WEB開發培訓PHP入門基礎課程 視頻教程 教學視頻 百度網盤下載
PHP基礎到高級開發自學視頻教程 教學視頻 百度網盤下載
PHP視頻教程之全面掌握smarty 視頻教程 教學視頻 百度網盤下載
PHP視頻教程之大型門戶網站核心技術—Mysql優化 視頻教程 教學視頻 百度網盤下載
ecshop二次開發視頻學習名師教程 ecshop仿站學習(附商城模版)
淘寶SDK專業教程
獨立實現ThinkPHP開發整站 前端+后台
PHP Yii2.0 框架打造完整電商平台教程
PHP培訓42期 基礎+就業
燕十八PHP高性能架構班培訓視頻 attach_img
Laravel5實戰開發在線圖書商城項目
CI框架課堂實錄 PHP CodeIgniter框架視頻教程
Laravel5.2從基礎到實戰博客項目開發
微信公眾平台PHP開發搭建與揭秘(附代碼)
ThinkPHP 3.2 全套視頻教程(+源碼)
PHP零基礎基礎到高級開發自學視頻培訓 視頻教程 教學視頻(價值1200元)
傳智播客-PHP從入門到精通視頻教程下載
泰牛PHP實戰開發教程全集 四大模塊全面出擊 最強PHP視頻教程
thinkphp實戰合集 視頻教程 教學視頻 百度網盤下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM