swoole2.0试用说明

    Swoole在2.0开始内置协程的能力,提供了具备协程能力IO接口.最好的好处是开发者可以以同步编码的方式达到异步IO的效果.

    Swoole2.0安装要求

  •      php版本要求:>= 5.5, 暂不支持PHP7
  •      基于swoole_server或者swoole_http_server进行开发,目前支持在onRequet, onReceive, onConnect回调中使用协程

    安装过程

  1. 先安装第三方的异步Redis库https://github.com/redis/hiredis   以支持redis操作
  2. 启用–enable-async-redis –enable-coroutine    

    安装常见问题

      1.找不到libhiredis.so.0.13 ,确保安装了hiredis前提下.增加/etc/ld.so.conf.d/lib.conf文件。内容”/usr/local/lib”.然后运行ldconfig命令

      2.gcc 4.4下如果在编译swoole的时候(即make阶段),出现gcc warning

        dereferencing pointer ‘v.327’ does break strict-aliasing rules、dereferencing type-punned pointer will break strict-aliasing rules

        请手动编辑Makefile,将CFLAGS = -Wall -pthread -g -O2替换为CFLAGS = -Wall -pthread -g -O2 -fno-strict-aliasing,

        然后重新编译make clean;make;make install

    安装完成后,请用php -m 来确认swoole是否安装成功.

    第一个代码示例.

<?php

$serv = new swoole\http\server("0.0.0.0", 1215);

$serv->set([
        'worker_num' => 1,
]);

$serv->on('Request', function($request, $response) {
    $response->header("X-Server", "Swoole");
    $cli = new Swoole\Coroutine\Http\Client('127.0.0.1', 80);
    $cli->setHeaders([
        'Host' => "test.xtgxiso.cn",
        "User-Agent" => 'Chrome/49.0.2587.3',
        'Accept' => 'text/html,application/xhtml+xml,application/xml',
        'Accept-Encoding' => 'gzip',
    ]);
    $cli->set([ 'timeout' => 2]);
    $cli->get('/sleep1.php');
    $str =  $cli->body;
    $cli->close();
 
    $response->end("<h1>Hello Swoole!</h1>".$str);
});

$serv->start();

    代码大致的功能是,以一个进程启动一个http server,访问一个url.这个url会sleep(1)

 模拟并发

<script src="http://123.56.145.253:1215/?id=1"></script>
<script src="http://123.56.145.253:1215/?id=2"></script>
<script src="http://123.56.145.253:1215/?id=3"></script>
<script src="http://123.56.145.253:1215/?id=4"></script>
<script src="http://123.56.145.253:1215/?id=5"></script>
<?php
echo "123";

   访问的效果

通过这个示例,我们已经可以明白swoole2.0的好处了。原来为了实现高并发,用的是IO复用,是各种回调。现在内置了协程,实现了高性能的同时代码看起来也是同步的!期待swoole2.0越来越强大.

   

此条目发表在 好文推荐, 网站开发 分类目录,贴了 标签。将固定链接加入收藏夹。

评论功能已关闭。