PHP的微服務其實和正常的crontab腳本區別不大,唯一的區別就是微服務可以自動判斷進程是否被殺死 殺死的話就會重啓
言語表達能力有限 廢話不多說 直接上代碼
<?php
/**
* 異步隊列拼單
* @author yjq
*/
include_once __DIR__ . ('/../../kis_lib_zhangyusport/load.php');
set_time_limit(0);
ini_set('memory_limit', '256M');
$argv[1]();
function check() {
$max = 1;
$buffer = array();
$buf = array();
$handle = popen ( "ps aux | grep 'asyncQueue/spelllog'| grep 'process' | grep -v grep | awk '{print $2}'", "r" );
while ( ! feof ( $handle ) ) {
$buffer = fgets ( $handle );
$buf[] = $buffer;
}
pclose($handle);
$han_cou = count($buf);
while ($han_cou <= $max) {
$path = dirname(__FILE__) . "/spelllog.php";
$coms = "nohup php {$path} process >> /tmp/spelllog.log 2>&1 &";
exec($coms);
$han_cou++;
}
unset($buffer,$buf);
}
function process(){
while (true){
$pid = pcntl_fork();
if ($pid == - 1) {
// 錯誤處理:創建子進程失敗時返回-1.
die('could not fork');
}else if($pid){
pcntl_waitpid($pid, $status);
}else{
try{
$list = lib_pay_plan_dao_order::getAppointTypeOrder();
hlp_log::log('spelllog','start:'.$list);
if($list){
lib_pay_plan_model_order::getNoCompleteSpell($list);
}
} catch (Exception $ex) {
hlp_log::log('spelllog',$ex->getMessage());
}
exit;
}
usleep(1000000);
}
}
1、check方法是運行整個微服務的,具體用法就是crontab
*/2 * * * * source /etc/profile && /usr/local/php/bin/php -f /opt/wwwroot/crontab.zhangyusport.com/asyncQueue/spelllog.php check > /dev/null 2>&1 &
每兩分鐘運行check一次就是讓微服務跑起來
2、process 就是進程代碼了
*注意 子父進程不能共用同一個數據庫鏈接 這樣會報錯的
3、上面的代碼只控制跑了一個進程 進程條數的控制在check方法裏面的 $max就代表是最大進程 usleep裏面的是微秒 切記是微秒 不是毫秒
下面再貼出2個進程的代碼。其實微服務也很簡單,就是要對linux的命令靈活運行和掌握才能寫出優秀的微服務
<?php
/**
* 異步隊列記錄投票日誌
* @author zs
*/
include_once __DIR__ . ('/../../kis_lib_zhangyusport/load.php');
set_time_limit(0);
ini_set('memory_limit', '256M');
$argv[1]();
function check() {
$max = 2;
$buffer = array();
$buf = array();
$handle = popen ( "ps aux | grep 'queue/votelog'| grep 'process' | grep -v grep | awk '{print $2}'", "r" );
while ( ! feof ( $handle ) ) {
$buffer = fgets ( $handle );
$buf[] = $buffer;
}
pclose($handle);
$han_cou = count($buf);
while ($han_cou <= $max) {
$path = dirname(__FILE__) . "/votelog.php";
$coms = "nohup php {$path} process >> /tmp/votelog.log 2>&1 &";
exec($coms);
$han_cou++;
}
unset($buffer,$buf);
}
function process(){
$queue_key = lib_queue_redis::queuekey_votlog;
while (true){
$message = lib_queue_redis::getItem($queue_key);
if($message){
excePid($message);
}else{
usleep(20000);
}
}
}
/**
* fork子線程執行邏輯
*/
function excePid($message){
$pid = pcntl_fork();
if ($pid == - 1) {
// 錯誤處理:創建子進程失敗時返回-1.
die('could not fork');
}else if($pid){
pcntl_waitpid($pid, $status);
}else{
try{
hlp_log::log('votelog_queue','start:'.$message);
$message = json_decode($message,true);
if(is_array($message)){
lib_news_model_vote::insertVotelog($message);
}
} catch (Exception $ex) {
hlp_log::log('votelog_queue',$ex->getMessage());
}
exit;
}
}