The content of this article is about swoole operation mode acceleration laravel application in detail, there is a certain reference value, there is a need for friends can refer to it, I hope to help you.

Swoole4 supports a full coroutine programming mode that allows asynchronous programs to be implemented using fully synchronous code. PHP code does not need to add any additional keywords, the bottom automatically coroutine scheduling, asynchronous IO. Swoole can achieve almost everything that NodeJS can achieve, and its performance is higher than NodeJS. After all, NodeJS is single-threaded and cannot give full play to CPU performance, while Swoole is multi-process and can give full play to CPU performance. What is the difference between Swoole efficiency and traditional Web development? In addition to traditional LAMP/LNMP synchronous development model, what is Swoole’s asynchronous development model and how to maintain efficiency?

Second, traditional Web development mode

The PHP Web development approach is LAMP/LNMP architecture, namely Linux, Nginx, Mysql and PHP. Here is an example of nginx:

When the request comes in,web serverForward the request toPHP-FPM.PHP-FPMIs a process pool architectureFastCGIService, built-in PHP interpreter. The FPM is responsible for interpreting the response generated by executing the PHP file, which is eventually returned to the Web Server for presentation to the front end. PHP files implement a lot of business logic, including Mysql and Nosql access, calling third party applications and so on. This structure of PHP-FPM and nginx works well enough, but because phP-FPM itself is a synchronous blocking process model that releases all resources (including a set of objects initialized by the framework) at the end of the request, the PHP process “idles” (create <–> destroy <–> create) and consumes a lot of CPU resources Source, resulting in a single machine throughput capacity is limited.

Each request processing process means a PHP file parsing, environment Settings and other unnecessary time-consuming operations in the PHP process to destroy the process, can not be used in THE PHP program to achieve performance optimization using connection pooling technology.

Swoole operation mode

Swoole addresses the traditional architecture problem by starting with PHP extensions, which we’ve already seen with swoole’s process model.

Compared with traditional architecture, the biggest characteristic of Swoole process model lies in its multithreaded Reactor model to deal with network requests, which makes it easy to deal with a large number of connections. In addition, the advantages also include: full asynchronous non-blocking, small occupation of resource overhead, high efficiency of program execution program only parse and load PHP files once, avoid repeated loading process resident each request, make connection pool and information transfer between requests possible

Why run Laravel on Swoole?

The Laravel framework had a lot of files to load when it started up, and because of its reputation for eco-friendliness, there were a lot of wheels that were already built during development, This makes Laravel’s disk IO for a boot extremely high (because there are so many files to load). The Laravel life cycle needs to be executed on every request. Because the environment created by a single request is destroyed immediately after the request is executed.

In other words, in the traditional PHP life cycle, a lot of time is wasted creating and destroying resources for script execution. Imagine a framework like Laravel. How many files need to be loaded per request? It also wastes a lot of I/O. So what if we use Swoole to build in an application-level Server, and all the script files are stored in memory once they’re loaded? That’s why we need to try running Laravel on Swoole. Swoole provides powerful performance while Laravel provides elegant code structures to use. These two make a perfect match!

Five, use Swoole to improve the performance of Laravel in the existing wheels, feel the following two or very good, can choose their own

swooletw/laravel-swoole
Copy the code
garveen/laravoole
Copy the code

I chose the first one to test using Composer installation:

composer require swooletw/laravel-swoole
Copy the code

If you are using Laravel, add it to the providers array in config/app.php

SwooleTW\Http\LaravelServiceProvider::class,
Copy the code

If you are using Lumen, add the following code to bootstrap/app.php

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

Export the configuration file to the config directory

php artisan vendor:publish --provider="SwooleTW\Http\HttpServiceProvider"
Copy the code

You can then go to config/swoole_http.php to configure the information

'server'= > ['host' => env('SWOOLE_HTTP_HOST'.'0.0.0.0'),// Listen on any IP address

        'port' => env('SWOOLE_HTTP_PORT'.'1215'),

        'options'= > ['pid_file' => env('SWOOLE_HTTP_PID_FILE', base_path('storage/logs/swoole_http.pid')),

            'log_file' => env('SWOOLE_HTTP_LOG_FILE', base_path('storage/logs/swoole_http.log')),

            'daemonize' => env('SWOOLE_HTTP_DAEMONIZE'.1),//1- The program will go into the background to run as a daemon]]Copy the code

Swoole_http.php also provides a configuration providers array,

'providers'= > [// App\Providers\AuthServiceProvider::class,

]
Copy the code

Because these providers are stored in memory using Swoole as HTTP, you configure providers that you want to re-register and restart on each request.

Now, you can execute the following command to start the Swoole HTTP service.

$ php artisan swoole:http start
Copy the code

You can then see the following message:

Starting swoole http server...

Swoole http server started: <http:/ / 0.0.0.0:1215 >
Copy the code

You can now access the Laravel app by visiting http://127.0.0.1:1215. Note: This extension does not support hot startup, so the service PHP artisan swoole: HTTP restart is restarted every time there isa code update

Performance test using Apache AB test tool

ab -n 1000 -c 10 http:/ / 127.0.0.1:1215 /
Copy the code

-n 1000 requests -c 10 concurrent requests

Figure 1 shows swoole as the application server, figure 2 shows the Apache server test environment. In the virtual machine, the computer configuration is also poor, and the performance is not fully developed. It can be seen that Apache can not withstand the pressure after only completing 197 requests. The apache server is completely overwhelmed.

Use the Nginx proxy

Swoole_http_server has incomplete support for Http and is recommended to be used only as an application server. And add Nginx as a proxy on the front end. Add server to nginx.conf:

server {
    listen 80;
    server_name your.domain.com;
    root /path/to/laravel/public;
    index index.php;
    location = /index.php {
        # Ensure that there is no such file named "not_exists"
        # in your "public" directory.
        try_files /not_exists @swoole;
    }
    location / {
        try_files $uri $uri/ @swoole;
    }
    location @swoole {
        set $suffix "";
        if ($uri = /index.php) {
            set $suffix "/";

        }
        proxy_set_header Host $host;
        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;
        # IF https
        # proxy_set_header HTTPS "on";
         proxy_pass http:/ / 127.0.0.1:1215 $suffix;}}Copy the code

The configuration can be done by referring to the Swoole documentation officer Nginx/Apache configuration and you’re done, and you can access your site as usual.

Disadvantages of using Swoole and traditional PHP development

This article mainly introduces the use of Swoole as the server for Laravel, and finally discusses the disadvantages of using Swoole and traditional PHP development. 1. Harder to get started. This requires developers to have a clearer understanding of the multi-process operation mode. 2. More prone to memory leaks. Be careful when handling global and static variables, because variables that are not cleaned up by the GC will last their entire life cycle and can easily run out of memory if not handled correctly. 3. Under PHP-FPM, PHP code is freed from memory after execution.

The above content hopes to help you, more free PHP factory PDF, PHP advanced architecture video materials, PHP wonderful good article can be wechat search concerns: PHP open source community

2021 Jinsanyin four big factory interview real questions collection, must see!

Four years of PHP technical articles collation collection – PHP framework

A collection of four years’ worth of PHP technical articles – Microservices Architecture

Distributed Architecture is a four-year collection of PHP technical articles

Four years of PHP technical essays – High Concurrency scenarios

Four years of elite PHP technical article collation collection – database