其他特性

配置Swoole事件

支持的事件列表:

事件需实现的接口发生时机
ServerStartHhxsv5\LaravelS\Swoole\Events\ServerStartInterface发生在Master进程启动时,此事件中不应处理复杂的业务逻辑,只能做一些初始化的简单工作
ServerStopHhxsv5\LaravelS\Swoole\Events\ServerStopInterface发生在Server正常退出时,此事件中不能使用异步或协程相关的API
WorkerStartHhxsv5\LaravelS\Swoole\Events\WorkerStartInterface发生在Worker/Task进程启动完成后
WorkerStopHhxsv5\LaravelS\Swoole\Events\WorkerStopInterface发生在Worker/Task进程正常退出后
WorkerErrorHhxsv5\LaravelS\Swoole\Events\WorkerErrorInterface发生在Worker/Task进程发生异常或致命错误时

1.创建事件处理类,实现相应的接口。

  1. namespace App\Events;
  2. use Hhxsv5\LaravelS\Swoole\Events\ServerStartInterface;
  3. use Swoole\Atomic;
  4. use Swoole\Http\Server;
  5. class ServerStartEvent implements ServerStartInterface
  6. {
  7. public function __construct()
  8. {
  9. }
  10. public function handle(Server $server)
  11. {
  12. // 初始化一个全局计数器(跨进程的可用)
  13. $server->atomicCount = new Atomic(2233);
  14. // 控制器中调用:app('swoole')->atomicCount->get();
  15. }
  16. }
  1. namespace App\Events;
  2. use Hhxsv5\LaravelS\Swoole\Events\WorkerStartInterface;
  3. use Swoole\Http\Server;
  4. class WorkerStartEvent implements WorkerStartInterface
  5. {
  6. public function __construct()
  7. {
  8. }
  9. public function handle(Server $server, $workerId)
  10. {
  11. // 初始化一个数据库连接池对象
  12. // DatabaseConnectionPool::init();
  13. }
  14. }

2.配置。

  1. // 修改文件 config/laravels.php
  2. 'event_handlers' => [
  3. 'ServerStart' => [\App\Events\ServerStartEvent::class], // 按数组顺序触发事件
  4. 'WorkerStart' => [\App\Events\WorkerStartEvent::class],
  5. ],

Serverless

阿里云函数计算

函数计算官方文档

1.修改bootstrap/app.php,设置storage目录。因为项目目录只读,/tmp目录才可读写。

  1. $app->useStoragePath(env('APP_STORAGE_PATH', '/tmp/storage'));

2.创建Shell脚本laravels_bootstrap,并赋予可执行权限

  1. #!/usr/bin/env bash
  2. set +e
  3. # 创建storage相关目录
  4. mkdir -p /tmp/storage/app/public
  5. mkdir -p /tmp/storage/framework/cache
  6. mkdir -p /tmp/storage/framework/sessions
  7. mkdir -p /tmp/storage/framework/testing
  8. mkdir -p /tmp/storage/framework/views
  9. mkdir -p /tmp/storage/logs
  10. # 设置环境变量APP_STORAGE_PATH,请确保与.env的APP_STORAGE_PATH一样
  11. export APP_STORAGE_PATH=/tmp/storage
  12. # Start LaravelS
  13. php bin/laravels start

3.配置template.xml

  1. ROSTemplateFormatVersion: '2015-09-01'
  2. Transform: 'Aliyun::Serverless-2018-04-03'
  3. Resources:
  4. laravel-s-demo:
  5. Type: 'Aliyun::Serverless::Service'
  6. Properties:
  7. Description: 'LaravelS Demo for Serverless'
  8. fc-laravel-s:
  9. Type: 'Aliyun::Serverless::Function'
  10. Properties:
  11. Handler: laravels.handler
  12. Runtime: custom
  13. MemorySize: 512
  14. Timeout: 30
  15. CodeUri: ./
  16. InstanceConcurrency: 10
  17. EnvironmentVariables:
  18. BOOTSTRAP_FILE: laravels_bootstrap