swoole利用task分发任务案例(群发短信)

利用了swoole监听其他的端口9502实现对task的任务分发

swoole的代码

<?php

namespace app\common;
include 'Predis.php';
include 'Task.php';
/**
*    socket面向对象的编译
*/
class Ws
{
    CONST HOST='0.0.0.0';
    CONST PORT='9501';
    public $ws=null;
    public $getmsg=null;
    public $server=null;

    public function __construct()
    {   
        $this->ws=new \swoole_websocket_server(self::HOST,self::PORT);
        $this->ws->set([
            //启动task必须要设置其数量
            'worker_num' => 4,
            'task_worker_num' => 2,
        ]);
        //监听新端口
        $this->server=$this->ws->listen("127.0.0.1", 9502, SWOOLE_SOCK_TCP);
        //关闭websocket模式
        $this->server->set([
            'open_websocket_protocol' => false,
        ]);

        $this->ws->on("start", [$this, 'onStart']);
        $this->ws->on('open',[$this,'onopen']);
        $this->server->on("receive", [$this, 'onReceive']);
        $this->ws->on('task',[$this,'onTask']);
        $this->ws->on('finish',[$this,'onFinish']);
        $this->ws->on('message',[$this,'onmessage']);
        $this->ws->on('close',[$this,'onclose']);
        $this->server->on("close", [$this, 'onclose']);
        $this->ws->start();
    }
    //监听数据接收事件
    public function onReceive($serv, $fd, $from_id, $data)
    {
        $shuju=json_decode($data,ture);
        // print_r($shuju).PHP_EOL;
        if (empty($shuju['data'])) {
            $this->ws->push(Predis::getInstance()->get('fd'), $data);
        }else{
            //执行异步任务
            $this->ws->task($shuju);
            // $this->ws->push(Predis::getInstance()->get('fd'), '异步任务开始了');
        }
    }
    /**
     * 设置进程名,为后续平滑重启进程
     * @param $server
     */
    public function onStart($server) {
        swoole_set_process_name("live_master");
    }      
   /**
        监听开启事件的回调
    */
    public function onopen($server, $request)
    {
        Predis::getInstance()->set('fd',$request->fd);
    }
    
    /**
        监听接收事件的回调
    */
    public function onmessage($server, $frame)
    {
        $server->push($frame->fd, "{$frame->data}");
    }
    /**
        监听关闭事件的回调
    */
    public function onclose($ser, $fd)
    {
        print_r("你好,我的{$fd}\n");
    }

    /**
    *   $serv           服务
    *   $task_id        任务ID,由swoole扩展内自动生成,用于区分不同的任务
    *   $src_worker_id  $task_id和$src_worker_id组合起来才是全局唯一的,不同的worker进程投递的任务ID可能会有相同
    *   $data           是任务的内容
    */
     public function onTask($serv,$task_id,$src_worker_id,$data)
    {
        //引入任务
        $obj = new Task;
        $method = $data['data'];
        foreach ($data['arr'] as $v) {
            $flag = $obj->$method($v, $serv);
        }
        return $flag; // 告诉worker
    }
    /**
    *   $task_id        是任务的ID
    *   $data           是任务处理的结果内容
    */
     public function onFinish($serv,$task_id,$data)
    {
        print_r($data).'/n';
    }

}

new Ws();


include 'Task.php';

<?php
/**
 * 代表的是  swoole里面 后续 所有  task异步 任务 都放这里来
 * Date: 18/3/27
 * Time: 上午1:20
 */
namespace app\common;
use app\common\redis\Predis;
// include 'Han.php';
class Task {

    // public function __construct()
    // {  
    //     $han= new Han;
    // }

    /**
     * 通过task机制测试
     * @param $data
     * @param $serv swoole server对象
     */
    public function pushLive($data, $serv) {
        // 在终端输出
        print_r($data).'/n';
        //执行耗时任务
        sleep(10);
        //回调于onFinish
        return '你成了-A';
    }
    /**
    *发送短信
    *
    */
    public function duanx($mobile,$serv,$tpl_id='62971')
    {
        // header('content-type:text/html;charset=utf-8');
        $code=rand(111111,999999);
        $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL
        $smsConf = array(
            'key'   => '0da7b818ef071ee9cXXXXXXXXXXXX', //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => $tpl_id, //您申请的短信模板ID,根据实际情况修改
            'tpl_value' =>'#code#='.$code //您设置的模板变量,根据实际情况修改
        );
        $content = self::juhecurl($sendUrl,$smsConf,1); //请求发送短信
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0,说明短信发送成功
                return $code;
            }else{
                //状态非0,说明失败
                $msg = $result['reason'];
                return ;
            }
        }else{
            //返回内容异常,以下可根据业务逻辑自行修改
            return ;
        }
    }

    public function juhecurl($url,$params=false,$ispost=0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}

include 'Predis.php';

<?php
/**
 * Created by PhpStorm.
 * User: baidu
 * Date: 18/3/26
 * Time: 上午3:52
 */
namespace app\common;

class Predis {
    public $redis = "";
    /**
     * 定义单例模式的变量
     * @var null
     */
    private static $_instance = null;

    public static function getInstance() {
        if(empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        $this->redis = new \Redis();
        $result = $this->redis->connect('127.0.0.1',6379);
        if($result === false) {
            throw new \Exception('redis connect error');
        }
    }

    /**
     * set
     * @param $key
     * @param $value
     * @param int $time
     * @return bool|string
     */
    public function set($key, $value, $time = 0 ) {
        if(!$key) {
            return '';
        }
        if(is_array($value)) {
            $value = json_encode($value);
        }
        if(!$time) {
            return $this->redis->set($key, $value);
        }

        return $this->redis->setex($key, $time, $value);
    }

    /**
     * get
     * @param $key
     * @return bool|string
     */
    public function get($key) {
        if(!$key) {
            return '';
        }

        return $this->redis->get($key);
    }

    /**
     * @param $key
     * @return array
     */
    public function sMembers($key) {
        return $this->redis->sMembers($key);
    }

    /**
     * @param $name
     * @param $arguments
     * @return array
     */
    public function __call($name, $arguments) {
        //echo $name.PHP_EOL;
        //print_r($arguments);
        if(count($arguments) != 2) {
            return '';
        }
        $this->redis->$name($arguments[0], $arguments[1]);
    }
}


控制器

<?php
namespace app\index\controller;
use app\commom\Ws;
use app\common\Client;

class Index
{

    //推送异步短信
    public function renwu()
    {
        $cli=new Client();
        $cli->data=[
            'data'=>'duanx',
            'arr'=>['1823407XXXX','1391110XXXX']
        ];
        $cli->lianjie();
        echo '你猜对了!';
    }
}


use app\common\Client;


<?php
namespace app\common;

class Client
{
    public $msg='';

    public $data=[];

    public function lianjie(){
        $cli = new \swoole_client(SWOOLE_TCP);
        //判断连接状态(同步连接模式)
        if ($cli->connect('127.0.0.1', 9502)) {
            echo "成功";
        }else{
            echo "失败";
        }
        if (!empty($this->data)) {
        	//发送消息给server
        	$rel=$cli->send(json_encode($this->data));
        }else{
        	//发送消息给server
        	$rel=$cli->send($this->msg);
        }
        
        echo $rel;
    }
}


猜你喜欢

转载自blog.csdn.net/feiwutudou/article/details/80289374