Use thinphp / swoole extension package

I wanted to own adaptation, but since keng looks like a lot, so decisively choose to adapt the official package 233. . .

Default conditions:. Thinkphp5.1 * next version, and extensions installed swoole

The main task of the demo task delivery

First, install

composer require topthink/think-swoole=2.0.*

Second, the use

If you want to run swoole http server to start thinkPHP framework, execution

php think swoole

After the default startup is complete, it will start a HTTP Server in 0.0.0.0:9501, the current application can be accessed directly.

swoole parameters can be arranged in the application directory  swoole.php inside configuration, the configuration as detailed  thinkPHP official website

Extended defined  onWorkerStartand  onRequestevent callback method (if unfamiliar Please do not replace), if you need to customize the swooleevent callback method can be used in the configuration file closure definition.

The following is my configuration (customized task task callbacks):

use App \ the Common \ lib \ utils \ Task;
 use of Think \ the Facade \ Env;
 use of Think \ the Facade \ the Log ; 

// + ---------------------- ------------------------------------------------ 
// | next Swoole set php think swoole effective command line 
// + ------------------------------------- --------------------------------- 
return [
     // expand their configuration 
    'host' => '0.0.0.0' , // listen address 
    'port' => 9501, // listening port 
    'mODE' => '', // run mode default SWOOLE_PROCESS 
    'sock_type' => '', //sock type defaults to SWOOLE_SOCK_TCP 
    'server_type' => 'HTTP', // type of service the WebSocket support HTTP 
    'app_path' => '', // application address If you turn 'daemonize' => true must be set (using an absolute path) 
    ' file_monitor '=> to false , // is turned PHP monitoring file changes (automatically open the debug mode) 
    ' file_monitor_interval '=> 2, // file monitoring changes in the detection time interval (in seconds) 
    ' file_monitor_path '=> [], // file the default directory monitoring and surveillance application config directory 

    for all configuration parameters // can support swoole of 
    'pid_file the' => Env :: GET ( 'runtime_path'). 'swoole.pid',get('root_path') . 'public',
    'enable_static_handler' => true 
    'log_file' => Env ::get('runtime_path') . 'swoole.log',
    'DOCUMENT_ROOT' => the Env :: GET ( 'the root_path'). 'public', , 
    'Timer' => to true , // whether to open the system timer 
    'interval The' => 500, // the system timer interval 
    'task_worker_num '=> 1, // number swoole mission work processes / * * 
     * custom delivery tasks 
     * @param swoole_server $ Serv 
     * @param int $ taskId 
     * @param int $ srcWorkerId 
     * @param the Data Mixed $ * / 
    ' task '= > function ( $ Serv , $ taskId , $ srcWorkerId ,$ data ) {
         $ taskObj

    
      = new new Task ();
        ClassMethods $ = get_class_methods (:: the Task class );
         IF (! the in_array ( $ Data [ 'Method'], $ ClassMethods )) {
             return 'Method:'. $ Data [ 'Method'] 'Not Find in'.Task. :: class ; 
        } 
        return  call_user_func_array ([ $ taskObj , $ Data [ 'method']], $ Data [ 'the params' ]); 
    } ,
     / * * 
     * onTask event no methods or return call finish a result, worker process does not triggers onFinish 
     * @Param swoole_server $ Serv
     * @Param int ID $ taskId tasks 
     * @param string $ data contents of the task processing result 
     * / 
    'Finish' => function ( $ Serv , $ taskld , $ Data ) {
 //         echo 'taskld:' $ taskld.. value is PHP_EOL; 
        echo 'Finished:'. $ Data ;
         the Log :: Record ( $ Data ); 
    } 
];

 

Achieve the task of delivering two methods ()

Index controllers:

<?php

namespace app\index\controller;

use app\common\lib\task\SmsTask;
use app\common\lib\utils\Tool;use think\Controller;
use think\Request;

class Index extends Controller
{
public function sendSms(Request $request) { $result = $this->validate($request->post(), ['mobile' => 'require|mobile']); if (true !== $result) { return Tool::json('', Result $ , 250 ); } $ Mobile = $ Request -> POST ( 'Mobile' ); // . 1, using topthink / swoole with Task delivery mode, or pass parameters must be subject swoole callback // $ smsObj = SmsTask new new ($ Mobile); // app ( 'swoole') -> task ($ smsObj); // app ( 'swoole') -> task ($ smsObj); // 2, custom task drop- app ( 'swoole') -> Task (Tool :: taskParam ( 'sendSms', ( Array ) $ Mobile )); return Tool :: JSON (' ',' send messages successfully " ); }

 

SmsTask.php

Use the system default callback template,

And the delivery parameter must be an object or swoole callback function,

After delivery default task execution run () method or the callback function swoole

<?php


namespace app\common\lib\task;

use Fairy\SmsSender;
use think\facade\Config;
use think\swoole\template\Task;

/**
 * 使用 topthink/swoole 自带的Task任务
 * Class SmsTask
 * @package app\common\lib\task
 */
class SmsTask extends Task
{
    private $mobile;

    public function initialize($args)
    {
        // TODO: Implement initialize() method.
        $this->mobile = $args[0];
    }

    public function run($serv, $taskId, $fromWorkerId)
    {
        // TODO: Implement run() method.
        $smsObj = SmsSender::getInstance(Config::get('mail.'));
        $bool = $smsObj->send($this->mobile);
        if ($bool) {
            return 'send sms to ' . $this->mobile . ' success';
        } else {
            return $smsObj->getError();
        }
    }
}

 

Task.php

Swoole.php with custom callback function using the task

<?php

namespace app\common\lib\utils;

use Fairy\SmsSender;use think\facade\Config;

/**
 * 异步任务类
 * Class Task
 * @package app\common\lib\utils
 */
class Task
{
    /**
     * 异步发送短信
     * @param $mobile
     * @return mixed|string
     * @throws \ErrorException
     */
    public function sendSms($mobile)
    {
        $smsObj = SmsSender::getInstance(Config::get('sms.'));
        $bool = $smsObj->send($mobile);
        if ($bool) {
            return 'send sms to ' . $mobile . ' success';
        } else {
            return 'send sms to ' . $mobile . ' failed: ' . $smsObj->getError();
        }
    }
}

 

Asynchronously send SMS execution process (task take custom exemplified):

  1. Custom configuration task function swoole.php
  2. Access Controller index / index / sendSms under index () method will deliver a task, Task to pass some parameters, then the interface data is returned and transmitted messages have been posted tasks
  3. callback task, which is to perform the task swoole.php configuration function
  4. Execution finish callback
  5. Kick call it a day, you got it

 

reference:

https://www.kancloud.cn/manual/thinkphp5_1/675277

Guess you like

Origin www.cnblogs.com/cshaptx4869/p/11360093.html