CentOS 6 无法安装 Swoole 提示 GCC 4.8 or later required

自行编译安装 gcc,依然提示,

当使用 gcc -v 提示已安装 gcc version 4.8.2

但使用 yum install gcc 提示是 4.4 且为最新版本

解决办法,卸载 yum 版 gcc,然后重新编译安装

yum remove gcc

CentOS 6 升级安装gcc 4.8

https://blog.csdn.net/bdss58/article/details/78175892

1. 导入CERN’s GPG key

rpm --import http://linuxsoft.cern.ch/cern/slc68/x86_64/RPM-GPG-KEY-cern

2. 添加slc6-devtoolset yum源

wget -O /etc/yum.repos.d/slc6-devtoolset.repo http://linuxsoft.cern.ch/cern/devtoolset/slc6-devtoolset.repo

3. 安装devtoolset-2

yum install devtoolset-2

4. 生效devtoolset-2

source /opt/rh/devtoolset-2/enable

可以将此命令写入.bashrc中,以免每次手动执行

echo 'source /opt/rh/devtoolset-2/enable' >> ~/.bashrc

验证一下gcc版本:

$ gcc --version
gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-15)
...

Swoole 编译报错 fatal error: hiredis/hiredis.h: No such file or directory

Swoole 当使用参数 --enable-async-redis 时编译报错

/tmp/pear/temp/swoole/swoole_redis.c:20:29: fatal error: hiredis/hiredis.h: No such file or directory

启用 Swoole 的 async-redis 扩展需要安装 hiredis,hiredis 需要 redis

安装 Redis

cd ~
wget http://download.redis.io/releases/redis-5.0.0.tar.gz
tar xzf redis-5.0.0.tar.gz
cd redis-5.0.0
make

安装 hiredis

cd ~
wget https://github.com/redis/hiredis/archive/v0.13.3.zip
unzip v0.13.3.zip
cd hiredis-0.13.3
make -j
sudo make install
sudo ldconfig
https://blog.liuguofeng.com/archives/3666

Swoole 编译错误 Enable http2 support, require nghttp2 library

安装 nghttp2

In file included from /tmp/pear/temp/swoole/swoole.c:16:0:
/tmp/pear/temp/swoole/php_swoole.h:142:2: error: #error "Enable http2 support, require nghttp2 library."
 #error "Enable http2 support, require nghttp2 library."

swoole 的 http2 模块依赖  nghttp2库,安装即可

wget https://github.com/nghttp2/nghttp2/releases/download/v1.30.0/nghttp2-1.30.0.tar.bz2 
tar -jxvf nghttp2-1.30.0.tar.bz2 
cd nghttp2-1.30.0 
./configure
make
make install

安装 PostgreSQL

如未安装报错如下:

configure: error: Cannot find libpq-fe.h. Please confirm the libpq or specify correct PostgreSQL(libpq) installation path
ERROR: `/tmp/pear/temp/swoole/configure --with-php-config=/usr/local/php/bin/php-config --enable-sockets=yes --enable-openssl=yes --enable-http2=yes --enable-mysqlnd=yes --enable-coroutine-postgresql=yes --enable-debug-log=yes' failed

解决办法

yum -y install postgresql-devel

Swoole 绑定域名 80 端口 (Nginx 监听转发)

启动 Swoole 的 http server,可以使用 IP + 端口 进行访问

创建 Nginx 虚拟域名

vim swotp.liuguofeng.com.conf
server
    {
        listen 80;
        server_name swotp.liuguofeng.com ;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/swoole_thinkphp.liuguofeng.com;

        location / {
                if (!-e $request_filename) {
                proxy_pass http://127.0.0.1:8811;
                }
        }
    }

重启 Nginx,DNS 指向 IP 

Linux 下 ThinkPHP 与 Swoole 搭配 ThinkPHP 性能对比测试

ThinkPHP 5.0.21

Server Software:        nginx
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /
Document Length:        39 bytes

Concurrency Level:      10
Time taken for tests:   9.064 seconds
Complete requests:      1000
Failed requests:        0
Total transferred:      218000 bytes
HTML transferred:       39000 bytes
Requests per second:    110.33 [#/sec] (mean)
Time per request:       90.637 [ms] (mean)
Time per request:       9.064 [ms] (mean, across all concurrent requests)
Transfer rate:          23.49 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:    15   90  37.8     87     217
Waiting:       15   90  37.8     87     217
Total:         15   90  37.8     88     217

Swoole 搭配 ThinkPHP 5.0.21

Server Software:        swoole-http-server
Server Hostname:        127.0.0.1
Server Port:            9501

Document Path:          /
Document Length:        39 bytes

Concurrency Level:      10
Time taken for tests:   4.355 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      1870000 bytes
HTML transferred:       390000 bytes
Requests per second:    2296.38 [#/sec] (mean)
Time per request:       4.355 [ms] (mean)
Time per request:       0.435 [ms] (mean, across all concurrent requests)
Transfer rate:          419.36 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       6
Processing:     1    4   3.7      4     166
Waiting:        0    4   3.6      3     166
Total:          1    4   3.7      4     166

配置信息

Swoole 适配 ThinkPHP 5 ab 压力测试 与 原生 ThinkPHP 对比

swoole 适配 thinkphp 5.0.21

Server Software:        swoole-http-server
Server Hostname:        127.0.0.1
Server Port:            9501

Document Path:          /
Document Length:        39 bytes

Concurrency Level:      10
Time taken for tests:   2.378 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      1870000 bytes
HTML transferred:       390000 bytes
Requests per second:    4204.38 [#/sec] (mean)
Time per request:       2.378 [ms] (mean)
Time per request:       0.238 [ms] (mean, across all concurrent requests)
Transfer rate:          767.79 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       2
Processing:     1    2   1.2      2      21
Waiting:        1    2   1.1      2      21
Total:          1    2   1.1      2      21

与原生 ThinkPHP 对比

Server Software:        nginx/1.15.3
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /index.php
Document Length:        39 bytes

Concurrency Level:      10
Time taken for tests:   48.468 seconds
Complete requests:      10000
Failed requests:        0
Total transferred:      2020000 bytes
HTML transferred:       390000 bytes
Requests per second:    206.32 [#/sec] (mean)
Time per request:       48.468 [ms] (mean)
Time per request:       4.847 [ms] (mean, across all concurrent requests)
Transfer rate:          40.70 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    2  75.8      0    3611
Processing:     9   45  73.4     42    3651
Waiting:        9   45  73.4     42    3651
Total:          9   47 105.2     42    3651

原生 PHP 输出 hello world

Server Software:        nginx/1.15.3
Server Hostname:        127.0.0.1
Server Port:            8080

Document Path:          /hello_world.php
Document Length:        11 bytes

Concurrency Level:      10
Time taken for tests:   0.870 seconds
Complete requests:      5000
Failed requests:        0
Total transferred:      870000 bytes
HTML transferred:       55000 bytes
Requests per second:    5749.02 [#/sec] (mean)
Time per request:       1.739 [ms] (mean)
Time per request:       0.174 [ms] (mean, across all concurrent requests)
Transfer rate:          976.88 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       2
Processing:     1    2   0.5      1       5
Waiting:        1    1   0.4      1       4
Total:          1    2   0.5      2       5

本机配置

Swoole 适配 ThinkPHP 5.0.21

新增代码

server/http_server.php

<?php
/**
 * Created by PhpStorm.
 * User: guofeng
 * Date: 2018/9/8
 * Time: 上午11:21
 */

$http = new swoole_http_server('0.0.0.0',9501);
$http->set([
    'enable_static_handler'=>true,
    'document_root'=>'../public/static',
    'worker_num'=>4,
]);
$http->on('WorkerStart',function(swoole_server $server,$worker_id){
    // 定义应用目录
    define('APP_PATH', __DIR__ . '/../application/');
    // ThinkPHP 引导文件
    // 1. 加载基础文件
    require __DIR__ . '/../thinkphp/base.php';
});
$http->on('request',function ($request,$response) use($http){

    $_SERVER = [];
    if(isset($request->server)){
        foreach($request->server as $k => $v){
            $_SERVER[strtoupper($k)] = $v;
        }
    }

    if(isset($request->header)){
        foreach($request->header as $k => $v){
            $_SERVER[strtoupper($k)] = $v;
        }
    }

    $_GET = [];
    if(isset($request->get)){
        foreach($request->get as $k => $v){
            $_GET[$k] = $v;
        }
    }

    $_POST = [];
    if(isset($request->post)){
        foreach($request->post as $k => $v){
            $_POST[$k] = $v;
        }
    }

    // 2. 执行应用
    ob_start();

    try{
        think\App::run()->send();
    }catch (\Exception $e){
        //todo
    }

    $res = ob_get_contents();
    ob_end_clean();
    $response->end($res);
});
$http->start();

ThinkPHP 核心文件修改

thinkphp/library/think/Request.php

/**
 * 获取当前请求URL的pathinfo信息(含URL后缀)
 * @access public
 * @return string
 */
public function pathinfo()
{
    if(isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] !='/'){
        return ltrim($_SERVER['PATH_INFO'], '/');
    }
    //if (is_null($this->pathinfo)) {
        if (isset($_GET[Config::get('var_pathinfo')])) {
            // 判断URL里面是否有兼容模式参数
            $_SERVER['PATH_INFO'] = $_GET[Config::get('var_pathinfo')];
            unset($_GET[Config::get('var_pathinfo')]);
        } elseif (IS_CLI) {
            // CLI模式下 index.php module/controller/action/params/...
            $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
        }

        // 分析PATHINFO信息
        if (!isset($_SERVER['PATH_INFO'])) {
            foreach (Config::get('pathinfo_fetch') as $type) {
                if (!empty($_SERVER[$type])) {
                    $_SERVER['PATH_INFO'] = (0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])) ?
                    substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME'])) : $_SERVER[$type];
                    break;
                }
            }
        }
        $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
    //}
    return $this->pathinfo;
}
/**
 * 获取当前请求URL的pathinfo信息(不含URL后缀)
 * @access public
 * @return string
 */
public function path()
{
    //if (is_null($this->path)) {
        $suffix   = Config::get('url_html_suffix');
        $pathinfo = $this->pathinfo();
        if (false === $suffix) {
            // 禁止伪静态访问
            $this->path = $pathinfo;
        } elseif ($suffix) {
            // 去除正常的URL后缀
            $this->path = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo);
        } else {
            // 允许任何后缀访问
            $this->path = preg_replace('/\.' . $this->ext() . '$/i', '', $pathinfo);
        }
    //}
    return $this->path;
}

访问方式

命令行 启动

php http_server.php

访问地址

http://localhost:9501/?s=index/index/index
http://localhost:9501/index/index/index

升级 Swoole

pecl upgrade swoole

或重新编译安装 

https://blog.liuguofeng.com/php-source-code-compilation-and-installation-swoole-extension/

查看 Swoole 版本

[root@VM_0_2_centos ~]# php --ri swoole
PHP Warning:  Module 'swoole' already loaded in Unknown on line 0

swoole

swoole support => enabled
Version => 4.1.1
Author => Swoole Group[email: team@swoole.com]
coroutine => enabled
epoll => enabled
eventfd => enabled
signalfd => enabled
cpu affinity => enabled
spinlock => enabled
rwlock => enabled
pcre => enabled
zlib => enabled
mutex_timedlock => enabled
pthread_barrier => enabled
futex => enabled

Directive => Local Value => Master Value
swoole.enable_coroutine => On => On
swoole.aio_thread_num => 2 => 2
swoole.display_errors => On => On
swoole.use_namespace => On => On
swoole.use_shortname => On => On
swoole.fast_serialize => Off => Off
swoole.unixsock_buffer_size => 8388608 => 8388608

出现错误提示

PHP Warning:  Module 'swoole' already loaded in Unknown on line 0

打开 php.ini

vim /usr/local/php/etc/php.ini

查找 swoole,插件被载入了两次,删除一个即可,删除重启

Swoole 与 纯 PHP ab 压力测试

服务器配置

  • 操作系统CentOS 7.2 64位
  • CPU1 核
  • 内存2 GB
  • 公网带宽1 Mbps

Swoole  2.1.2-alpha

<?php
$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();
ab -c100 -n100000 http://127.0.0.1:9501/
Server Software:        nginx
Server Hostname:        127.0.0.1
Server Port:            80

Document Path:          /helloworld.php
Document Length:        11 bytes

Concurrency Level:      100
Time taken for tests:   20.609 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Total transferred:      18900000 bytes
HTML transferred:       1100000 bytes
Requests per second:    4852.13 [#/sec] (mean)
Time per request:       20.609 [ms] (mean)
Time per request:       0.206 [ms] (mean, across all concurrent requests)
Transfer rate:          895.56 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       3
Processing:     3   20   6.3     20     153
Waiting:        1   20   6.3     20     153
Total:          3   21   6.3     20     154

PHP 7.2.3

<?php
echo 'hello world';
ab -c100 -n100000 http://127.0.0.1/helloworld.php
Server Software:        swoole-http-server
Server Hostname:        127.0.0.1
Server Port:            9501

Document Path:          /
Document Length:        12 bytes

Concurrency Level:      100
Time taken for tests:   5.758 seconds
Complete requests:      100000
Failed requests:        0
Write errors:           0
Total transferred:      16100000 bytes
HTML transferred:       1200000 bytes
Requests per second:    17368.14 [#/sec] (mean)
Time per request:       5.758 [ms] (mean)
Time per request:       0.058 [ms] (mean, across all concurrent requests)
Transfer rate:          2730.73 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.4      1       4
Processing:     3    4   0.9      4      54
Waiting:        2    3   0.6      3      52
Total:          4    6   0.9      5      54

PHP7 源码编译安装 Swoole 扩展

cd ~/Downloads
git clone https://gitee.com/swoole/swoole.git
cd swoole
/home/misswell/soft/php/bin/phpize
./configure --with-php-config=/home/misswell/soft/php/bin/php-config
make -j
make install

或加上异步 redis

cd ~/Downloads 
git clone https://gitee.com/swoole/swoole.git
cd swoole 
/home/misswell/soft/php/bin/phpize
./configure --with-php-config=/home/misswell/soft/php/bin/php-config --enable-async-redis
make clean
make -j
make install

返回信息

...
Installing shared extensions: /home/misswell/soft/php/lib/php/extensions/no-debug-non-zts-20170718/
Installing header files: /home/misswell/soft/php/include/php/