Laravel octane installation swoole

Time:2021-9-27

What is larave octane

octaneyeslaravelThe official third-party package, which can be integratedSwooleandRoadRunnerThese two high-performance application servers are used to improve the performance of applications.

RoadRunnerItself is aGoOpen source languagePHPApplication server.
SwooleIs a useC++A parallel network communication engine based on asynchronous event driven and co process written inPHPProvide collaborative and high-performance network programming support.

AndApacheorNginxandPHP-FPMVery similar,HTTPRequests can be sent toRoadRunnerorSwooleTo executePHPCode, and then send the response back.RoadRunnerorSwooleThe difference is that it canPHPRunning applications are kept in memory for faster speed after the application starts. aboutLaravelThis is quite helpful.

Environmental requirements

  1. PHP 8.0+
  2. Larave 8.35+
  3. SwooleandRoadRunnerMust beunixInstallation under system (MacOS, Linux,window(WSL2)
  4. RoadRunner: please make surecurlzip socketsWait until the PHP extension is installed
  5. Local virtual machine, IP:192.168.2.11

Installation history

according toLaravelThe official documentation to installSwooleandRoadRunnerThe third-party package is a very painful thing, because there are often messy problems in the installation process. In order to reduce detours, it is necessary for me to emphasize several issues here.

  1. Be sure tounixInstalled under the system,unixSystem includesmacOS linuxandLinux subsystem of windows
  2. In order to access the virtual machine locally, please shut downlinuxfirewall

Step1. Installationoctanepackage

composer require laravel/octane

Suppose you already have a new onelaravelproject Enter the project root directory and execute the above command.

Step 2. Configure nginx agent

Why configure nginx’s proxy first?

Official documentsIt says:

The Octane server can be started via the octane:start Artisan command. By default, this command will utilize the server specified by the server configuration option of your application’s octane configuration file:

php artisan octane:start

By default, Octane will start the server on port 8000, so you may access your application in a web browser via http://localhost:8000.

This means that the default port is set after the startup command is executed8000, in the browserhttp://localhost:8000visit. But I passedhttp://192.168.2.11:8000But I can’t visit. Friends who know the reason of this problem can leave a message.

according toOfficial documentsofnginxto configure

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8009;            #  Port accessed by browser
    #listen [::]:80;
    server_name 127.0.0.1;
    server_tokens off;
    root /var/www/html/octane/public;

    index index.php;

    charset utf-8;

    location /index.php {
        try_files /not_exists @octane;
    }

    location / {
        try_files $uri $uri/ @octane;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log /var/log/nginx/octane-access.log main;
    error_log  /var/log/nginx/octane-error.log error;

    error_page 404 /index.php;

    location @octane {
        set $suffix "";

        if ($uri = /index.php) {
            set $suffix ?$query_string;
        }

        proxy_http_version 1.1;
        proxy_set_header Host $http_host;
        proxy_set_header Scheme $scheme;
        proxy_set_header SERVER_PORT $server_port;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        proxy_ pass  http://127.0.0.1:8010 $suffix;            #  Proxy request
    }
}

Note the notes in the above configuration:

  • listen 8009: is the port I will access in my browserhttp://192.168.2.11:8009
  • http://127.0.0.1:8010: YesoctanePort specified at startup

Step3. UseSwoole

1. InstallationSwooleextend

OctaneIs dependentSwooleExtended. phpSwooleExtended installation, you can find some tutorials on the Internet and install them.

2. ReleaseoctaneConfiguration file for

php artisan octane:install

This command will beconfigGenerated under directoryoctane.phpConfiguration file for

3. Start service

php artisan octane:start --server=swoole --port=8010

Output:

  INFO  Server running…

  Local: http://127.0.0.1:8010 

  Press Ctrl+C to stop the server

See these, explainoctaneIt has been started successfully.

4. Access in browser

Because we just configured itnginxProxy, just enter it in the browserhttp://192.168.2.11:8009And enter.
You can see that the command interface will appearGETRequest.

Laravel octane installation swoole

As can be seen from the above figure, the first request took 85.46ms, while the second request took only a few milliseconds, which greatly improved the speed.

Step4. AB pressure measurement

The following is the data of the liunx system on the virtual machine:

  1. View kernel version

    [[email protected] ~]# uname -r
    3.10.0-1160.41.1.el7.x86_64
  2. View CPU

    [[email protected] ~]# grep "model name" /proc/cpuinfo | cut -f2 -d:
    Intel(R) Core(TM) i5-10500 CPU @ 3.10GHz
    Intel(R) Core(TM) i5-10500 CPU @ 3.10GHz
  3. View CPU cores

    [[email protected] ~]# cat /proc/cpuinfo |grep "cores"|uniq
    cpu cores    : 2
  4. view memory

    [[email protected] ~]# grep MemTotal /proc/meminfo | cut -f2 -d:
    1863020 kB

Swoole pressure measurement

1. CreateusersTable:
CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `Role ` tinyint (3) unsigned not null default '2' comment 'Role: 1-administrator, 2-member...',
  `created_ At ` int (10) unsigned not null default '0' comment 'creation time',
  `updated_ At ` int (10) unsigned not null default '0' comment 'update time',
  `deleted_ At ` int (10) unsigned not null default '0' comment 'delete time',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_ INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_ unicode_ Ci comment = 'member table';
2. Modify the configuration file
# .env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=123456

3. Generate controller and write code

Generation controller

php artisan make:controller UserController

Write code

namspace App\Http\Controllers;

class UserController extends Controller
{
    public array $store = [];

    public function index(Request $request)
    {
        $nameList = ['james', 'lucy', 'jack', 'jessica', 'lily'];

        $name = $nameList[array_rand($nameList)];

        If (rand (0, 7) > = 2) {// 0-1 read 2-7 write
            $test = new User();
            $test->name = $name;
            $test->password = Hash::make(123456);
            $test->role = 2;
            $test->created_at = time();
            $test->updated_at = time();
            $test->deleted_at = time();
            $test->save();

            $data = ['id' => $test->id];
        } else {
            $data = User::query()->where('name', $name)->first();;
        }
    }
}
4. Add route
# web.php
Route::get('test-mysql', '[email protected]');
5. Start pressure measurement

Pressure measurement command

ab -n 1000 -c 8 http://127.0.0.1:8010/test-mysql
  • -n 1000: Specifies that the number of requests used by the test session is 1000
  • -c 8: 8 concurrent requests

useOctaneThe pressure test results are as follows:

[[email protected] octane]# ab -n 1000 -c 8 http://127.0.0.1:8010/test-mysql
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        
Server Hostname:        127.0.0.1
Server Port:            8010

Document Path:          /test-mysql
Document Length:        0 bytes

Concurrency Level:      8
Time taken for tests:   22.268 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      1048000 bytes
HTML transferred:       0 bytes
Requests per second:    44.91 [#/sec] (mean)
Time per request:       178.141 [ms] (mean)
Time per request:       22.268 [ms] (mean, across all concurrent requests)
Transfer rate:          45.96 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       1
Processing:    14  177  43.8    180     327
Waiting:       14  177  43.8    179     327
Total:         14  177  43.8    180     327

Percentage of the requests served within a certain time (ms)
  50%    180
  66%    195
  75%    207
  80%    217
  90%    230
  95%    241
  98%    254
  99%    261
 100%    327 (longest request)

Look again noOctanePressure test results at

Execute the command,8008It is a port configured separately by me, without going throughoctane

ab -n 1000 -c 8 http://127.0.0.1:8008/test-mysql

result:

[[email protected] octane]# ab -n 1000 -c 8 http://127.0.0.1:8008/test-mysql
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests


Server Software:        nginx/1.20.1
Server Hostname:        127.0.0.1
Server Port:            8008

Document Path:          /test-mysql
Document Length:        0 bytes

Concurrency Level:      8
Time taken for tests:   55.076 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      1134000 bytes
HTML transferred:       0 bytes
Requests per second:    18.16 [#/sec] (mean)
Time per request:       440.606 [ms] (mean)
Time per request:       55.076 [ms] (mean, across all concurrent requests)
Transfer rate:          20.11 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.0      0       0
Processing:    70  438 193.7    424    1587
Waiting:       70  438 193.7    424    1587
Total:         70  438 193.7    424    1588

Percentage of the requests served within a certain time (ms)
  50%    424
  66%    511
  75%    565
  80%    593
  90%    652
  95%    705
  98%    783
  99%   1183
 100%   1588 (longest request)

According to the comparison of the above two results,octaneThe speed has been significantly increased several times.

Step6. Advantages and disadvantages

1. Advantages

stayOctaneWe’ve been using it beforeNginx + PHP-FPMThe order of execution is:

  1. A request cameNginx
  2. NginxDelegate request toPHP-FPMPHP-FPMOr create a new onewoker, or use an existingwokerTo process the request.
  3. PHP-FPM workerStart the laravel application.
  4. LaravelYour application processes the request.
  5. PHP-FPMReturn results toNginxNginxReturns the output to the client.

As mentioned above, each request incurs overhead from the beginning of process creation and to the start of the laravel application. In step 4, the LaVale framework loads all the required dependencies, includingVendor package, Service Providers, MiddlewareandrouteWait, with a third partyserviceMore and more, the starting speed is more and more uncontrolled.

Laravel OctaneThe application is accelerated by starting the application once and resident in memory

2. Disadvantages

  1. Service container injection may not bind successfully
  2. The request parameters may be incorrect during HTTP request injection
  3. Memory leaks may occur

Conclusion:

Laravel OctaneThe new release is only a few months away. For many developers, it is not necessary, because many application bottlenecks are related to non optimized database queries, slow session storage or slow external storageAPIRequest related. If you want to use it in your own projectLaravel Octane, be prepared to encounter more headaches.

NextCan explainRoadRunnerUse of.