easyswoole-异步任务的使用注意

异步任务对于优化业务实现提高响应效率很有帮助。

http://easyswoole.com/Manual/2.x/Cn/_book/Advanced/async_task.html

投递闭包
use EasySwoole\Core\Swoole\Task\TaskManager;
TaskManager::async(function (){
    sleep(10);
    var_dump('this is async task');
});

由于php本身就不能序列化闭包,该闭包投递是通过反射该闭包函数,获取php代码直接序列化php代码,
然后直接eval代码实现的 所以投递闭包无法使用外部的对象引用,以及资源句柄,复杂任务请使用任务模板方法。

当任务比较复杂,逻辑较多而且固定时,可以预先创建任务模板,并直接投递任务模板,以简化操
作和方便在多个不同的地方投递相同的任务,首先需要创建一个任务模板。

最终选择 投递任务模板类 来完成复杂的业务。
在异步进程里无法再调用异步进程写日志,所以只能将原先的异步日志写法改成同步的了!!

实际使用中基本都是复杂业务,简单业务也没必要使用异步任务。

使用
use EasySwoole\Core\Swoole\Task\TaskManager;
$taskClass = new RegisterAfterTask($info);
TaskManager::async($taskClass);

定义 RegisterAfterTask
setPlayerPartnerAndAgent($taskData);
        $taskData['partner_id'] = $pInfo['partner_id'];
        $taskData['agent_id'] = $pInfo['agent_id'];

        $afterAction = RegisterAfterBlock::getInstance();
        $afterAction->addClass(AddChangeMoney::class);
        $afterAction->addClass(AddPromoteInfo::class);
        $afterAction->addClass(UpdatePlayerStatus::class);
        $afterAction->addClass(updateSubPlayerNum::class);

        $afterAction->doRegisterAfter($taskData);

        return true;
    }

    /**
     * 任务执行完的回调
     * @param mixed $result  任务执行完成返回的结果
     * @param int   $task_id 执行任务的task编号
     * @author : evalor 
     */
    function finish($result, $task_id)
    {
        // 任务执行完的处理
    }

    protected function setPlayerPartnerAndAgent($info){
        /*
         * vip归属
         * 1、VIP推广的归VIP自己。
         * 2、一层A推广的B,B随机VIP,或者归公司VIP
         * 3、B推广的C,C继承B的VIP
         *
         * 渠道归属
         * 1、渠道推广的归渠道自己,其他归公司渠道
        */

        $agent_id = 0;
        $partner_id = 0;

        if($info['partner_id']){
            $agent_id = RegisterPlayerBlock::DEFAULT_AGENT_ID;
            $partner_id = $info['partner_id'];
        }

        if($info['agent_id']){
            $agent_id = $info['agent_id'];
            $partner_id = RegisterPlayerBlock::DEFAULT_PARTNER_ID;
        }

        // b类玩家
        if($info['parent_id']){
            $partner_id = RegisterPlayerBlock::DEFAULT_PARTNER_ID;
            // 判断parent_id是二层,还是大于二层
            $parent = PromoteInfoModel::getInstance()->where('player_id', $info['parent_id'])->getOne();
            if($parent['level'] == 1){
                // 随机VIP
                $config = ConfigModel::getInstance()->config_list('open_vip_random');
                if($config['config_config']['is_open'] && Helper::getRate($config['config_config']['rate'])){
                    $ids = AgentInfoModel::getInstance()->where('status', 1)->getValue('id', null);
                    $agent_id = $ids[array_rand($ids)];
                }else{
                    $agent_id = RegisterPlayerBlock::DEFAULT_AGENT_ID;
                }
            }else{
                $agent_id = $parent['agent_id'];
            }
        }

        $re = ['agent_id'=>$agent_id, 'partner_id'=>$partner_id];

        return $re;
    }
}

你可能感兴趣的:(swoole)