My Blog Posts

Accelerate Your Laravel App with Swoole

Accelerate Your Laravel App with Swoole


Swoole is an asynchronous programming framework for PHP. It is a PHP extension written in pure C and allows PHP developers to write high-performance, scalable, simultaneous TCP, UDP, Unix socket, HTTP, IO programming that does not block WebSocket services in PHP, and gives you high performance in Swoole with a low Linux processor.

Why do we run Laravel in Swoole?

The following illustration shows the lifecycle in PHP. As you can see, every time you run the php script, PHP must start modules and start Zend Engine for your running environment. And your PHP script must be compiled into OpCodes for zend engine execution.

In other words, in the PHP lifecycle, it takes a lot of time to create and delete resources for scriptexecution. And in frameworks like Laravel, how many files do you need to upload for a request? There is also a lot of I/O consumption to load files.

So what happens if we have a built-in server on Swoole and all scripts can be kept in memory after the first installation? That's why we try to run it, swoole can be a powerful performance booster on laravel and Laravel provides easy build and code usage. This gives us the perfect combination.

Setup

Requesting this package with Composer:

$composer require swooletw/laravel-swoole

This package is based on the Swoole extension. Before using this package, make sure you set up Swoole.

Note: Swoole currently only supports Linux and OSX. Windows servers are not yet available to Swoole.

Then add the service provider:

Laravel add the service provider to the provider's array. config/app.php:

[
'providers' => [
SwooleTW\Http\LaravelServiceProvider::class,
],
]

Lumen if you are using it , add the following code bootstrap/app.php:

$app->register(SwooleTW\Http\LumenServiceProvider::class);

If you're running Laravel 5.5and above, you can skip this step.

You can now run the following command to start the Swoole HTTP server.

$ php artisan swoole:http start

Then you can see the following message:

Starting swoole http server...
Swoole started http server:

You can now access your Laravel app at this address.


Nginx Http Server

Running 10s test @ http://lumen.app:9999
4 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 1.14s 191.03ms 1.40s 90.31%
Req/Sec 22.65 10.65 50.00 65.31%
815 requests in 10.07s, 223.65KB read
Requests/sec: 80.93
Transfer/sec: 22.21KB

Swoole HTTP Server

Running 10s test @ http://127.0.0.1:1215
4 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 11.58ms 4.74ms 68.73ms 81.63%
Req/Sec 2.19k 357.43 2.90k 69.50%
87879 requests in 10.08s, 15.67MB read
Requests/sec: 8717.00
Transfer/sec: 1.55MB

For more information, see the package in Github RepoWater and Official Documents.



Share this article


Comments (0)

Comment