PHP code example of yangweijie / think-runtime

1. Go to this page and download the library: Download yangweijie/think-runtime library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yangweijie / think-runtime example snippets



return [
    // 默认运行时 (auto, swoole, roadrunner)
    'default' => 'auto',

    // 自动检测顺序
    'auto_detect_order' => [
        'swoole',
        'frankenphp',
        'workerman',
        'reactphp',
        'roadrunner',
        'bref',
        'vercel',
    ],

    // 运行时配置
    'runtimes' => [
        'swoole' => [
            'host' => '0.0.0.0',
            'port' => 9501,
            'settings' => [
                'worker_num' => 4,
                'task_worker_num' => 2,
                'max_request' => 10000,
            ],
        ],
        'roadrunner' => [
            'debug' => false,
            'max_jobs' => 0,
        ],
    ],
];


use yangweijie\thinkRuntime\runtime\RuntimeManager;

// 获取运行时管理器
$manager = app('runtime.manager');

// 自动检测并启动
$manager->start();

// 指定运行时启动
$manager->start('swoole', [
    'host' => '0.0.0.0',
    'port' => 9501,
]);

// 获取运行时信息
$info = $manager->getRuntimeInfo();


use yangweijie\thinkRuntime\contract\AdapterInterface;
use yangweijie\thinkRuntime\runtime\AbstractRuntime;

class CustomAdapter extends AbstractRuntime implements AdapterInterface
{
    public function getName(): string
    {
        return 'custom';
    }

    public function isSupported(): bool
    {
        return true;
    }

    public function getPriority(): int
    {
        return 50;
    }

    // 实现其他必需方法...
}

// 注册自定义适配器
$manager = app('runtime.manager');
$manager->registerAdapter('custom', CustomAdapter::class);

'swoole' => [
    'host' => '0.0.0.0',           // 监听地址
    'port' => 9501,                // 监听端口
    'mode' => 3,                   // 运行模式 (SWOOLE_PROCESS)
    'sock_type' => 1,              // Socket类型 (SWOOLE_SOCK_TCP)
    'settings' => [
        'worker_num' => 4,          // Worker进程数
        'task_worker_num' => 2,     // Task进程数
        'max_request' => 10000,     // 最大请求数
        'dispatch_mode' => 2,       // 数据包分发策略
        'daemonize' => 0,          // 守护进程化
        'enable_coroutine' => 1,    // 启用协程
        'max_coroutine' => 100000,  // 最大协程数
        'hook_flags' => 268435455,  // 协程Hook标志 (SWOOLE_HOOK_ALL)
        'enable_preemptive_scheduler' => true, // 启用抢占式调度
    ],
    // 静态文件配置
    'static_file' => [
        'enable' => true,           // 启用静态文件服务
        'document_root' => 'public', // 文档根目录
        'cache_time' => 3600,       // 缓存时间(秒)
        'allowed_extensions' => ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico', 'svg'], // 允许的文件扩展名
    ],
    // WebSocket 配置
    'websocket' => [
        'enable' => false,          // 启用WebSocket支持
    ],
    // 性能监控配置
    'monitor' => [
        'enable' => true,           // 启用性能监控
        'slow_request_threshold' => 1000, // 慢请求阈值(毫秒)
    ],
    // 中间件配置
    'middleware' => [
        'cors' => [
            'enable' => true,       // 启用CORS中间件
            'allow_origin' => '*',  // 允许的源
            'allow_methods' => 'GET, POST, PUT, DELETE, OPTIONS', // 允许的方法
            'allow_headers' => 'Content-Type, Authorization, X-Requested-With', // 允许的头
        ],
        'security' => [
            'enable' => true,       // 启用安全中间件
        ],
    ],
],

'frankenphp' => [
    'listen' => ':8080',           // 监听地址和端口
    'worker_num' => 4,             // Worker进程数
    'max_requests' => 1000,        // 每个Worker最大请求数
    'auto_https' => true,          // 自动HTTPS
    'http2' => true,               // 启用HTTP/2
    'http3' => false,              // 启用HTTP/3
    'debug' => false,              // 调试模式
    'access_log' => true,          // 访问日志
    'error_log' => true,           // 错误日志
    'log_level' => 'INFO',         // 日志级别
    'root' => 'public',            // 文档根目录
    'index' => 'index.php',        // 入口文件
    'env' => [                     // 环境变量
        'APP_ENV' => 'production',
    ],
],

'reactphp' => [
    'host' => '0.0.0.0',           // 监听主机
    'port' => 8080,                // 监听端口
    'max_connections' => 1000,     // 最大连接数
    'timeout' => 30,               // 连接超时时间(秒)
    'enable_keepalive' => true,    // 启用Keep-Alive
    'keepalive_timeout' => 5,      // Keep-Alive超时时间
    'max_request_size' => '8M',    // 最大请求大小
    'enable_compression' => true,  // 启用压缩
    'debug' => false,              // 调试模式
    'access_log' => true,          // 访问日志
    'error_log' => true,           // 错误日志
    'websocket' => false,          // WebSocket支持
    'ssl' => [                     // SSL配置
        'enabled' => false,
        'cert' => '',              // SSL证书路径
        'key' => '',               // SSL私钥路径
    ],
],

'roadrunner' => [
    'host' => '0.0.0.0',           // 监听主机
    'port' => 8080,                // 监听端口
    'worker_num' => 4,             // Worker进程数
    'max_connections' => 10000,    // 最大连接数
    'timeout' => 30,               // 连接超时时间(秒)
    'enable_keepalive' => true,    // 启用Keep-Alive
    'keepalive_timeout' => 60,     // Keep-Alive超时时间
    'max_request_size' => '8M',    // 最大请求大小
    'enable_compression' => true,  // 启用压缩
    'compression_level' => 6,      // 压缩级别
    'debug' => false,              // 调试模式
    'access_log' => true,          // 访问日志
    'error_log' => true,           // 错误日志
    'enable_fiber' => true,        // 启用Fiber
    'fiber_stack_size' => 8192,    // Fiber栈大小
    'ssl' => [                     // SSL配置
        'enabled' => false,
        'cert_file' => '',         // SSL证书文件
        'key_file' => '',          // SSL私钥文件
        'verify_peer' => false,    // 验证对等方
    ],
    'database' => [                // 数据库连接池
        'pool_size' => 10,         // 连接池大小
        'max_idle_time' => 3600,   // 最大空闲时间
    ],
],

'roadrunner' => [
    'debug' => false,      // 调试模式
    'max_jobs' => 0,       // 最大任务数 (0为无限制)
    'memory_limit' => '128M', // 内存限制
],

'workerman' => [
    'host' => '0.0.0.0',           // 监听地址
    'port' => 8080,                // 监听端口
    'count' => 4,                  // 进程数
    'name' => 'ThinkPHP-Workerman', // 进程名称
    'user' => '',                  // 运行用户
    'group' => '',                 // 运行用户组
    'reloadable' => true,          // 是否可重载
    'reusePort' => false,          // 端口复用
    'transport' => 'tcp',          // 传输协议
    'context' => [],               // Socket上下文选项
    'protocol' => 'http',          // 应用层协议
    // 静态文件配置
    'static_file' => [
        'enable' => true,           // 启用静态文件服务
        'document_root' => 'public', // 文档根目录
        'cache_time' => 3600,       // 缓存时间(秒)
        'allowed_extensions' => ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico', 'svg'], // 允许的文件扩展名
    ],
    // 性能监控配置
    'monitor' => [
        'enable' => true,           // 启用性能监控
        'slow_request_threshold' => 1000, // 慢请求阈值(毫秒)
        'memory_limit' => '256M',   // 内存限制
    ],
    // 中间件配置
    'middleware' => [
        'cors' => [
            'enable' => true,       // 启用CORS中间件
            'allow_origin' => '*',  // 允许的源
            'allow_methods' => 'GET, POST, PUT, DELETE, OPTIONS', // 允许的方法
            'allow_headers' => 'Content-Type, Authorization, X-Requested-With', // 允许的头
        ],
        'security' => [
            'enable' => true,       // 启用安全中间件
        ],
    ],
    // 日志配置
    'log' => [
        'enable' => true,           // 启用日志
        'file' => 'runtime/logs/workerman.log', // 日志文件
        'level' => 'info',          // 日志级别
    ],
    // 定时器配置
    'timer' => [
        'enable' => false,          // 启用定时器
        'interval' => 60,           // 定时器间隔(秒)
    ],
],

'bref' => [
    // Lambda运行时配置
    'lambda' => [
        'timeout' => 30,               // Lambda函数超时时间(秒)
        'memory' => 512,               // Lambda函数内存大小(MB)
        'environment' => 'production', // 运行环境
    ],
    // HTTP处理配置
    'http' => [
        'enable_cors' => true,         // 启用CORS
        'cors_origin' => '*',          // 允许的源
        'cors_methods' => 'GET, POST, PUT, DELETE, OPTIONS', // 允许的方法
        'cors_headers' => 'Content-Type, Authorization, X-Requested-With', // 允许的头
    ],
    // 错误处理配置
    'error' => [
        'display_errors' => false,     // 显示错误
        'log_errors' => true,          // 记录错误日志
    ],
    // 性能监控配置
    'monitor' => [
        'enable' => true,              // 启用性能监控
        'slow_request_threshold' => 1000, // 慢请求阈值(毫秒)
    ],
],

'vercel' => [
    // Vercel函数配置
    'vercel' => [
        'timeout' => 10,               // Vercel函数超时时间(秒)
        'memory' => 1024,              // 函数内存大小(MB)
        'region' => 'auto',            // 部署区域
        'runtime' => 'php-8.1',        // PHP运行时版本
    ],
    // HTTP处理配置
    'http' => [
        'enable_cors' => true,         // 启用CORS
        'cors_origin' => '*',          // 允许的源
        'cors_methods' => 'GET, POST, PUT, DELETE, OPTIONS', // 允许的方法
        'cors_headers' => 'Content-Type, Authorization, X-Requested-With', // 允许的头
        'max_body_size' => '5mb',      // 最大请求体大小
    ],
    // 错误处理配置
    'error' => [
        'display_errors' => false,     // 显示错误
        'log_errors' => true,          // 记录错误日志
        'error_reporting' => E_ALL & ~E_NOTICE, // 错误报告级别
    ],
    // 性能监控配置
    'monitor' => [
        'enable' => true,              // 启用性能监控
        'slow_request_threshold' => 1000, // 慢请求阈值(毫秒)
        'memory_threshold' => 80,      // 内存使用阈值百分比
    ],
    // 静态文件配置
    'static' => [
        'enable' => false,             // 启用静态文件服务(Vercel通常由CDN处理)
        'extensions' => ['css', 'js', 'png', 'jpg', 'jpeg', 'gif', 'ico', 'svg'], // 允许的文件扩展名
    ],
],



declare(strict_types=1);

/**
 * RoadRunner Worker 入口文件
 */

use think\App;
use yangweijie\thinkRuntime\runtime\RuntimeManager;

// 引入自动加载
dRunner运行时
$manager->start('roadrunner');

   'settings' => [
       'worker_num' => 4,              // 设置为CPU核心数
       'max_request' => 10000,         // 防止内存泄漏
       'enable_coroutine' => 1,        // 启用协程
       'max_coroutine' => 100000,      // 根据内存调整
   ]
   

   'static_file' => [
       'enable' => true,
       'cache_time' => 86400,          // 24小时缓存
       'allowed_extensions' => ['css', 'js', 'png', 'jpg'], // 限制文件类型
   ]
   

   'monitor' => [
       'slow_request_threshold' => 500, // 500ms慢请求阈值
   ]
   

   'max_connections' => 1000,          // 根据服务器配置调整
   'timeout' => 30,                    // 合理的超时时间
   'enable_keepalive' => true,         // 启用长连接
   

   'max_request_size' => '8M',         // 限制请求大小
   'enable_compression' => true,       // 启用压缩
   

   'count' => 4,                       // 设置为CPU核心数
   'reloadable' => true,               // 启用平滑重启
   'reusePort' => true,                // 启用端口复用(Linux 3.9+)
   

   'static_file' => [
       'enable' => true,
       'cache_time' => 86400,          // 24小时缓存
       'allowed_extensions' => ['css', 'js', 'png', 'jpg'], // 限制文件类型
   ]
   

   'monitor' => [
       'slow_request_threshold' => 500, // 500ms慢请求阈值
       'memory_limit' => '256M',        // 内存限制
   ]
   

   // Bref
   'lambda' => [
       'timeout' => 30,                // 合理的超时时间
       'memory' => 1024,               // 根据需求调整内存
   ]

   // Vercel
   'vercel' => [
       'timeout' => 10,                // Vercel限制
       'memory' => 1024,               // 最大内存
   ]
   

   'monitor' => [
       'slow_request_threshold' => 1000, // 考虑冷启动时间
   ]
   
bash
# 方案1: 重新发现服务
php think service:discover
php think clear

# 方案2: 手动注册(运行项目根目录下的脚本)
php vendor/yangweijie/think-runtime/test-thinkphp-commands.php
bash
# 自动安装 ReactPHP 依赖
php vendor/yangweijie/think-runtime/install-reactphp.php

# 或手动安装
composer 
bash
# 自动检测并启动最佳运行时
php think runtime:start

# 指定运行时启动
php think runtime:start swoole
php think runtime:start frankenphp
php think runtime:start workerman
php think runtime:start reactphp
php think runtime:start bref
php think runtime:start vercel

# 自定义参数启动
php think runtime:start swoole --host=127.0.0.1 --port=8080 --workers=8
php think runtime:start frankenphp --port=8080 --workers=4
php think runtime:start workerman --host=0.0.0.0 --port=8080 --workers=4
php think runtime:start reactphp --host=0.0.0.0 --port=8080
bash
php think runtime:info
yaml
# .rr.yaml
version: "3"

rpc:
  listen: tcp://127.0.0.1:6001

server:
  command: "php worker.php"
  user: ""
  group: ""
  env:
    - APP_ENV: production
  relay: "pipes"
  relay_timeout: "20s"

http:
  address: 0.0.0.0:8080
  middleware: ["static", "gzip"]
  uploads:
    forbid: [".php", ".exe", ".bat"]
  static:
    dir: "public"
    forbid: [".htaccess", ".php"]

logs:
  mode: development
  level: error
  file_logger_options:
    log_output: "./runtime/logs/roadrunner.log"
    max_size: 10
    max_age: 30
    max_backups: 3
    compress: true

reload:
  interval: "1s"
  patterns: [".php"]
  services:
    http:
      recursive: true
      ignore: ["vendor"]
      patterns: [".php"]
      dirs: ["./"]
bash
# 通过 PECL 安装
pecl install swoole

# 或通过包管理器安装(Ubuntu/Debian)
sudo apt-get install php-swoole

# 或通过包管理器安装(CentOS/RHEL)
sudo yum install php-swoole

# 验证安装
php -m | grep swoole
ini
extension=swoole
bash
# 通过 Composer 安装
composer ists('Workerman\\Worker') ? 'OK' : 'Failed';"
bash
# 通过 Composer 安装
composer xists('React\\EventLoop\\Loop') ? 'EventLoop: OK' : 'EventLoop: Failed';
echo PHP_EOL;
echo class_exists('React\\Http\\HttpServer') ? 'HttpServer: OK' : 'HttpServer: Failed';
"
bash
# 检查 PHP 版本
php -v  # 确保 >= 8.1

# 通过 Composer 安装
composer ersion: OK' : 'PHP Version: Failed';
echo PHP_EOL;
echo class_exists('Ripple\\Http\\Server') ? 'Ripple: OK' : 'Ripple: Failed';
"
bash
# 安装 RoadRunner 二进制文件
curl -fsSL https://github.com/roadrunner-server/roadrunner/releases/latest/download/roadrunner-linux-amd64.tar.gz | tar -xz
sudo mv rr /usr/local/bin/

# 通过 Composer 安装 PHP 包
composer Spiral\\RoadRunner\\Worker') ? 'OK' : 'Failed';"
bash
# 通过 Composer 安装
composer ists('Bref\\Context\\Context') ? 'OK' : 'Failed';"
bash
AWS_LAMBDA_FUNCTION_NAME=your-function
AWS_LAMBDA_RUNTIME_API=127.0.0.1:9001
_LAMBDA_SERVER_PORT=8080
bash
   # 检查扩展是否加载
   php -m | grep swoole

   # 检查 php.ini 配置
   php --ini
   
bash
   # 检查二进制文件
   which frankenphp

   # 检查环境变量
   echo $FRANKENPHP_VERSION
   
bash
php think runtime:start [runtime] [options]
bash
# 自动检测最佳运行时
php think runtime:start

# 启动Swoole服务器
php think runtime:start swoole --host=127.0.0.1 --port=8080 --workers=8 --debug

# 启动ReactPHP服务器
php think runtime:start reactphp --port=8080 --debug

# 启动FrankenPHP服务器
php think runtime:start frankenphp --port=8080 --workers=4 --debug

# 启动Workerman服务器
php think runtime:start workerman --port=8080 --workers=4 --daemon

# 启动RoadRunner服务器
php think runtime:start roadrunner --debug

# 启动Bref服务器(AWS Lambda环境)
php think runtime:start bref --debug

# 启动Vercel服务器(Vercel Serverless环境)
php think runtime:start vercel --debug
bash
php think runtime:info
bash
   # Ubuntu/Debian
   sudo apt-get install php-swoole

   # CentOS/RHEL
   sudo yum install php-swoole

   # 或使用PECL安装
   pecl install swoole
   
bash
   # 查看端口占用
   netstat -tlnp | grep 9501

   # 或使用其他端口
   php think runtime:start swoole --port=8080