继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Swoole Accidence Second(入门)

侠客岛的含笑
关注TA
已关注
手记 133
粉丝 1.6万
获赞 1807
异步非堵塞IO场景

swoole毫秒定时器

  • crontab
// 每2秒执行
            swoole_timer_tick(2000, function($timer_id){
                echo "2s: timerId:{$timer_id}\n";
            });
// 一次性执行
swoole_timer_after(5000, function() use($ws, $frame) {
            echo "5s-after\n";
            $ws->push($frame->fd, "server-time-after:");
        });

异步文件系统IO-读取文件

>swoole_async_readfile默认最大读取4MB

/**
 * 读取文件
 * __DIR__
 */
// 后执行
$result = Swoole\Async::readfile(__DIR__."/1.txt", function($filename, $fileContent) {
    echo "filename:".$filename.PHP_EOL;  // \n \r\n
    echo "content:".$fileContent.PHP_EOL;
});
// 先执行
var_dump($result); // 如果文件存在返回true
echo "start".PHP_EOL;

异步文件系统IO-写文件

$content = date("Ymd H:i:s").PHP_EOL;
swoole_async_writefile(__DIR__."/1.log", $content, function($filename){
    // todo
    echo "success".PHP_EOL;
// 追加方式写入
}, FILE_APPEND);
// file_put_contents();
echo "start".PHP_EOL;

异步mysql

class AysMysql {
    /**
     * @var string
     */
    public $dbSource = "";
    /**
     * mysql的配置
     * @var array
     */
    public $dbConfig = [];
    public function __construct() {
        //new swoole_mysql;
        $this->dbSource = new Swoole\Mysql;

        $this->dbConfig = [
            'host' => '127.0.0.1',
            'port' => 5123,
            'user' => 'root',
            'password' => 123456,
            'database' => 'swoole',
            'charset' => 'utf8',
        ];
    }

    public function update() {

    }

    public function add() {

    }

    /**
     * mysql 执行逻辑
     * @param $id
     * @param $username
     * @return bool
     */
    public function execute($id, $username) {
        // connect
        $this->dbSource->connect($this->dbConfig, function($db, $result) use($id, $username)  {
            echo "mysql-connect".PHP_EOL;
            if($result === false) {
                var_dump($db->connect_error);
                // todo
            }

            // $sql = "select * from test where id=1";
            $sql = "update test set `username` = '".$username."' where id=".$id;
            // insert into
            // query (add select update delete)
            $db->query($sql, function($db, $result){
                // select => result返回的是 查询的结果内容

                if($result === false) {
                    // todo
                    var_dump($db->error);
                }elseif($result === true) {// add update delete
                    // todo
                    var_dump($db->affected_rows);
                }else { //select
                    print_r($result);
                }
                $db->close();
            });

        });
        return true;
    }
}
$obj = new AysMysql();
$flag = $obj->execute(1, 'hanxiao-1');
var_dump($flag).PHP_EOL;
echo "start".PHP_EOL;

for($i=0; $i<900000;$i++) {
    echo $i.PHP_EOL;
}

异步Redis

查看是否成功支持异步Redis php --ri swoole

图片描述

$redisClient = new swoole_redis;// Swoole\Redis
$redisClient->connect('127.0.0.1', 6379, function(swoole_redis $redisClient, $result) {
    echo "connect".PHP_EOL;
    var_dump($result);

    // 同步 redis (new Redis())->set('hanxiao_1',time());
    /*$redisClient->set('hanxiao_1', time(), function(swoole_redis $redisClient, $result) {
        var_dump($result);
    });*/

    /*$redisClient->get('hanxiao_1', function(swoole_redis $redisClient, $result) {
        var_dump($result);
        $redisClient->close();
    });*/
    $redisClient->keys('*gw*', function(swoole_redis $redisClient, $result) {
        var_dump($result);
        $redisClient->close();
    });

});

echo "start".PHP_EOL;

进程

Linux 查看 pid pstree -p 父进程id
ps aft | grep 执行的文件名

$process = new swoole_process(function(swoole_process $pro) {
    // todo
    // php http_server.php
    $pro->exec("/home/work/study/soft/php/bin/php", [__DIR__.'/../server/http_server.php']);
}, false);

$pid = $process->start();
echo $pid . PHP_EOL;

swoole_process::wait();

图片描述

echo "process-start-time:".date("Ymd H:i:s");
$workers = [];
$urls = [
    'http://baidu.com',
    'http://sina.com.cn',
    'http://qq.com',
    'http://baidu.com?search=hanxiao',
    'http://baidu.com?search=hanxiao2',
    'http://baidu.com?search=imooc',
];

for($i = 0; $i < 6; $i++) {
    // 子进程
    $process = new swoole_process(function(swoole_process $worker) use($i, $urls) {
        // curl
        $content = curlData($urls[$i]);
        //echo $content.PHP_EOL;
        $worker->write($content.PHP_EOL);
    }, true);
    $pid = $process->start();
    $workers[$pid] = $process;
}

foreach($workers as $process) {
    echo $process->read();
}
/**
 * 模拟请求URL的内容  1s
 * @param $url
 * @return string
 */
function curlData($url) {
    // curl file_get_contents
    sleep(1);
    return $url . "success".PHP_EOL;
}
echo "process-end-time:".date("Ymd H:i:s");

内存

// 创建内存表
$table = new swoole_table(1024);

// 内存表增加一列
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING, 64);
$table->column('age', $table::TYPE_INT, 3);
$table->create();

$table->set('hanxiao_imooc', ['id' => 1, 'name'=> 'hanxiao', 'age' => 30]);
// 另外一种方案
$table['hanxiao_imooc_2'] = [
    'id' => 2,
    'name' => 'hanxiao2',
    'age' => 31,
];

$table->decr('hanxiao_imooc_2', 'age', 2);
print_r($table['hanxiao_imooc_2']);

echo "delete start:".PHP_EOL;
$table->del('hanxiao_imooc_2');

print_r($table['hanxiao_imooc_2']);

协程

>类似并发调用,redis和mysql一起同时调用,只取其中的最大的时间调用值

$http = new swoole_http_server('0.0.0.0', 8001);

$http->on('request', function($request, $response) {
    // 获取redis 里面 的key的内容, 然后输出浏览器

    $redis = new Swoole\Coroutine\Redis();
    $redis->connect('127.0.0.1', 6379);
    $value = $redis->get($request->get['a']);

    $response->header("Content-Type", "text/plain");
    $response->end($value);
});

$http->start();

登录模块

直播模块

聊天室模块

系统监控和性能优化模块

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP