Download the PHP package hhxsv5/laravel-s without Composer
On this page you can find all versions of the php package hhxsv5/laravel-s. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download hhxsv5/laravel-s
More information about hhxsv5/laravel-s
Files in hhxsv5/laravel-s
Package laravel-s
Short Description π LaravelS is an out-of-the-box adapter between Laravel/Lumen and Swoole.
License MIT
Homepage https://github.com/hhxsv5/laravel-s
Rated 5.00 based on 9 reviews
Informations about the package laravel-s
π LaravelS is an out-of-the-box adapter between Laravel/Lumen and Swoole
Continuous Updates
- Please
Watch
this repository to get the latest updates.
Table of Contents
- Features
- Benchmark
- Requirements
- Install
- Run
- Deploy
- Cooperate with Nginx (Recommended)
- Cooperate with Apache
- Enable WebSocket server
- Listen events
- System events
- Customized asynchronous events
- Asynchronous task queue
- Millisecond cron job
- Automatically reload after modifying code
- Get the instance of SwooleServer in your project
- Use SwooleTable
- Multi-port mixed protocol
- Coroutine
- Custom process
- Common components
- Apollo
- Prometheus
- Other features
- Configure Swoole events
- Serverless
- Important notices
- Users and cases
- Alternatives
- Sponsor
- License
Features
-
Built-in Http/WebSocket server
-
Memory resident
-
Gracefully reload
-
Support Laravel/Lumen both, good compatibility
- Simple & Out of the box
Benchmark
Requirements
Dependency | Requirement |
---|---|
PHP | >=8.2 Recommend 8.2 |
Swoole | >=5.0 Recommend 5.1.1 |
Laravel/Lumen | >=10 Recommend 10 |
Install
1.Require package via Composer(packagist).
2.Register service provider(pick one of two).
-
Laravel
: inconfig/app.php
file,Laravel 5.5+ supports package discovery automatically, you should skip this step
Lumen
: inbootstrap/app.php
file
3.Publish configuration and binaries.
After upgrading LaravelS, you need to republish; click here to see the change notes of each version.
4.Change config/laravels.php
: listen_ip, listen_port, refer Settings.
5.Performance tuning
-
Number of Workers: LaravelS uses Swoole's
Synchronous IO
mode, the larger theworker_num
setting, the better the concurrency performance, but it will cause more memory usage and process switching overhead. If one request takes 100ms, in order to provide 1000QPS concurrency, at least 100 Worker processes need to be configured. The calculation method is: worker_num = 1000QPS/(1s/1ms) = 100, so incremental pressure testing is needed to calculate the bestworker_num
. - Number of Task Workers
Run
Please read the notices carefully before running
, Important notices(IMPORTANT).
- Commands:
php bin/laravels {start|stop|restart|reload|info|help}
.
Command | Description |
---|---|
start | Start LaravelS, list the processes by "ps -ef|grep laravels" |
stop | Stop LaravelS, and trigger the method onStop of Custom process |
restart | Restart LaravelS: Stop gracefully before starting; The service is unavailable until startup is complete |
reload | Reload all Task/Worker/Timer processes which contain your business codes, and trigger the method onReload of Custom process, CANNOT reload Master/Manger processes. After modifying config/laravels.php , you only have to call restart to restart |
info | Display component version information |
help | Display help information |
- Boot options for the commands
start
andrestart
.
Option | Description |
---|---|
-d|--daemonize | Run as a daemon, this option will override the swoole.daemonize setting in laravels.php |
-e|--env | The environment the command should run under, such as --env=testing will use the configuration file .env.testing firstly, this feature requires Laravel 5.2+ |
-i|--ignore | Ignore checking PID file of Master process |
-x|--x-version | The version(branch) of the current project, stored in $_ENV/$_SERVER, access via $_ENV['X_VERSION'] $_SERVER['X_VERSION'] $request->server->get('X_VERSION') |
Runtime
files:start
will automatically executephp artisan laravels config
and generate these files, developers generally don't need to pay attention to them, it's recommended to add them to.gitignore
.
File | Description |
---|---|
storage/laravels.conf | LaravelS's runtime configuration file |
storage/laravels.pid | PID file of Master process |
storage/laravels-timer-process.pid | PID file of the Timer process |
storage/laravels-custom-processes.pid | PID file of all custom processes |
Deploy
It is recommended to supervise the main process through Supervisord, the premise is without option
-d
and to setswoole.daemonize
tofalse
.
Cooperate with Nginx (Recommended)
Demo.
Cooperate with Apache
Enable WebSocket server
The Listening address of WebSocket Sever is the same as Http Server.
1.Create WebSocket Handler class, and implement interface WebSocketHandlerInterface
.The instant is automatically instantiated when start, you do not need to manually create it.
2.Modify config/laravels.php
.
3.Use SwooleTable
to bind FD & UserId, optional, Swoole Table Demo. Also you can use the other global storage services, like Redis/Memcached/MySQL, but be careful that FD will be possible conflicting between multiple Swoole Servers
.
4.Cooperate with Nginx (Recommended)
Refer WebSocket Proxy
5.Heartbeat setting
-
Heartbeat setting of Swoole
- Proxy read timeout of Nginx
6.Push data in controller
Listen events
System events
Usually, you can reset/destroy some
global/static
variables, or change the currentRequest/Response
object.
-
laravels.received_request
After LaravelS parsedSwoole\Http\Request
toIlluminate\Http\Request
, before Laravel's Kernel handles this request. laravels.generated_response
After Laravel's Kernel handled the request, before LaravelS parsesIlluminate\Http\Response
toSwoole\Http\Response
.
Customized asynchronous events
This feature depends on
AsyncTask
ofSwoole
, your need to setswoole.task_worker_num
inconfig/laravels.php
firstly. The performance of asynchronous event processing is influenced by number of Swoole task process, you need to set task_worker_num appropriately.
1.Create event class.
2.Create listener class.
3.Fire event.
Asynchronous task queue
This feature depends on
AsyncTask
ofSwoole
, your need to setswoole.task_worker_num
inconfig/laravels.php
firstly. The performance of task processing is influenced by number of Swoole task process, you need to set task_worker_num appropriately.
1.Create task class.
2.Deliver task.
Millisecond cron job
Wrapper cron job base on Swoole's Millisecond Timer, replace
Linux
Crontab
.
1.Create cron job class.
2.Register cron job.
3.Note: it will launch multiple timers when build the server cluster, so you need to make sure that launch one timer only to avoid running repetitive task.
4.LaravelS v3.4.0
starts to support the hot restart [Reload] Timer
process. After LaravelS receives the SIGUSR1
signal, it waits for max_wait_time
(default 5) seconds to end the process, then the Manager
process will pull up the Timer
process again.
5.If you only need to use minute-level
scheduled tasks, it is recommended to enable Hhxsv5\LaravelS\Illuminate\LaravelScheduleJob
instead of Linux Crontab, so that you can follow the coding habits of Laravel task scheduling and configure Kernel
.
Automatically reload after modifying code
-
Via
inotify
, support Linux only.1.Install inotify extension.
2.Turn on the switch in Settings.
3.Notice: Modify the file only in
Linux
to receive the file change events. It's recommended to use the latest Docker. Vagrant Solution. -
Via
fswatch
, support OS X/Linux/Windows.1.Install fswatch.
2.Run command in your project root directory.
-
Via
inotifywait
, support Linux.1.Install inotify-tools.
2.Run command in your project root directory.
- When the above methods does not work, the ultimate solution: set
max_request=1,worker_num=1
, so thatWorker
process will restart after processing a request. The performance of this method is very poor,so only development environment use
.
Get the instance of SwooleServer
in your project
Use SwooleTable
1.Define Table, support multiple.
All defined tables will be created before Swoole starting.
2.Access Table
: all table instances will be bound on SwooleServer
, access by app('swoole')->xxxTable
.
Multi-port mixed protocol
For more information, please refer to Swoole Server AddListener
To make our main server support more protocols not just Http and WebSocket, we bring the feature multi-port mixed protocol
of Swoole in LaravelS and name it Socket
. Now, you can build TCP/UDP
applications easily on top of Laravel.
-
Create
Socket
handler class, and extendHhxsv5\LaravelS\Swoole\Socket\{TcpSocket|UdpSocket|Http|WebSocket}
.These
Socket
connections share the same worker processes with yourHTTP
/WebSocket
connections. So it won't be a problem at all if you want to deliver tasks, useSwooleTable
, even Laravel components such as DB, Eloquent and so on. At the same time, you can accessSwoole\Server\Port
object directly by member propertyswoolePort
. -
Register Sockets.
About the heartbeat configuration, it can only be set on the
main server
and cannot be configured onSocket
, but theSocket
inherits the heartbeat configuration of themain server
.For TCP socket,
onConnect
andonClose
events will be blocked whendispatch_mode
of Swoole is1/3
, so if you want to unblock these two events please setdispatch_mode
to2/4/5
. - Test.
-
TCP:
telnet 127.0.0.1 5291
- UDP: [Linux]
echo "Hello LaravelS" > /dev/udp/127.0.0.1/5292
-
Register example of other protocols.
-
UDP
-
Http
- WebSocket: The main server must
turn on WebSocket
, that is, setwebsocket.enable
totrue
.
-
Coroutine
-
Warning: The order of code execution in the coroutine is out of order. The data of the request level should be isolated by the coroutine ID. However, there are many singleton and static attributes in Laravel/Lumen, the data between different requests will affect each other, it's
Unsafe
. For example, the database connection is a singleton, the same database connection shares the same PDO resource. This is fine in the synchronous blocking mode, but it does not work in the asynchronous coroutine mode. Each query needs to create different connections and maintain IO state of different connections, which requires a connection pool. DO NOT
enable the coroutine, only the custom process can use the coroutine.
Custom process
Support developers to create special work processes for monitoring, reporting, or other special tasks. Refer addProcess.
-
Create Proccess class, implements CustomProcessInterface.
-
Register TestProcess.
-
Note: The callback() cannot quit. If quit, the Manager process will re-create the process.
- Example: Write data to a custom process.
Common components
Apollo
LaravelS
will pull theApollo
configuration and write it to the.env
file when starting. At the same time,LaravelS
will start the custom processapollo
to monitor the configuration and automaticallyreload
when the configuration changes.
-
Enable Apollo: add
--enable-apollo
and Apollo parameters to the startup parameters. -
Support hot updates(optional).
- List of available parameters.
Parameter | Description | Default | Demo |
---|---|---|---|
apollo-server | Apollo server URL | - | --apollo-server=http://127.0.0.1:8080 |
apollo-app-id | Apollo APP ID | - | --apollo-app-id=LARAVEL-S-TEST |
apollo-namespaces | The namespace to which the APP belongs, support specify the multiple | application | --apollo-namespaces=application --apollo-namespaces=env |
apollo-cluster | The cluster to which the APP belongs | default | --apollo-cluster=default |
apollo-client-ip | IP of current instance, can also be used for grayscale publishing | Local intranet IP | --apollo-client-ip=10.2.1.83 |
apollo-pull-timeout | Timeout time(seconds) when pulling configuration | 5 | --apollo-pull-timeout=5 |
apollo-backup-old-env | Whether to backup the old configuration file when updating the configuration file .env |
false | --apollo-backup-old-env |
Prometheus
Support Prometheus monitoring and alarm, Grafana visually view monitoring metrics. Please refer to Docker Compose for the environment construction of Prometheus and Grafana.
-
Require extension APCu >= 5.0.0, please install it by
pecl install apcu
. -
Copy the configuration file
prometheus.php
to theconfig
directory of your project. Modify the configuration as appropriate.If your project is
Lumen
, you also need to manually load the configuration$app->configure('prometheus');
inbootstrap/app.php
. -
Configure
global
middleware:Hhxsv5\LaravelS\Components\Prometheus\RequestMiddleware::class
. In order to count the request time consumption as accurately as possible,RequestMiddleware
must be thefirst
global middleware, which needs to be placed in front of other middleware. -
Register ServiceProvider:
Hhxsv5\LaravelS\Components\Prometheus\ServiceProvider::class
. -
Configure the CollectorProcess in
config/laravels.php
to collect the metrics of Swoole Worker/Task/Timer processes regularly. -
Create the route to output metrics.
-
Complete the configuration of Prometheus and start it.
- Start Grafana, then import panel json.
Other features
Configure Swoole events
Supported events:
Event | Interface | When happened |
---|---|---|
ServerStart | Hhxsv5\LaravelS\Swoole\Events\ServerStartInterface | Occurs when the Master process is starting, this event should not handle complex business logic, and can only do some simple work of initialization . |
ServerStop | Hhxsv5\LaravelS\Swoole\Events\ServerStopInterface | Occurs when the server exits normally, CANNOT use async or coroutine related APIs in this event . |
WorkerStart | Hhxsv5\LaravelS\Swoole\Events\WorkerStartInterface | Occurs after the Worker/Task process is started, and the Laravel initialization has been completed. |
WorkerStop | Hhxsv5\LaravelS\Swoole\Events\WorkerStopInterface | Occurs after the Worker/Task process exits normally |
WorkerError | Hhxsv5\LaravelS\Swoole\Events\WorkerErrorInterface | Occurs when an exception or fatal error occurs in the Worker/Task process |
1.Create an event class to implement the corresponding interface.
2.Configuration.
Serverless
Alibaba Cloud Function Compute
1.Modify bootstrap/app.php
and set the storage directory. Because the project directory is read-only, the /tmp
directory can only be read and written.
2.Create a shell script laravels_bootstrap
and grant executable permission
.
3.Configure template.xml
.
Important notices
Singleton Issue
-
Under FPM mode, singleton instances will be instantiated and recycled in every request, request start=>instantiate instance=>request end=>recycled instance.
-
Under Swoole Server, All singleton instances will be held in memory, different lifetime from FPM, request start=>instantiate instance=>request end=>do not recycle singleton instance. So need developer to maintain status of singleton instances in every request.
-
Common solutions:
-
Write a
XxxCleaner
class to clean up the singleton object state. This class implements the interfaceHhxsv5\LaravelS\Illuminate\Cleaners\CleanerInterface
and then registers it incleaners
oflaravels.php
. -
Reset
status of singleton instances byMiddleware
. - Re-register
ServiceProvider
, addXxxServiceProvider
intoregister_providers
of filelaravels.php
. So that reinitialize singleton instances in every request Refer.
-
Cleaners
Known issues
Known issues: a package of known issues and solutions.
Debugging method
-
Logging; if you want to output to the console, you can use
stderr
, Log::channel('stderr')->debug('debug message'). - Laravel Dump Server(Laravel 5.7 has been integrated by default).
Read request
Read request by Illuminate\Http\Request
Object, $_ENV is readable, $_SERVER is partially readable, CANNOT USE
$_GET/$_POST/$_FILES/$_COOKIE/$_REQUEST/$_SESSION/$GLOBALS.
Output response
Respond by Illuminate\Http\Response
Object, compatible with echo/vardump()/print_r()οΌCANNOT USE
functions dd()/exit()/die()/header()/setcookie()/http_response_code().
Persistent connection
Singleton connection
will be resident in memory, it is recommended to turn on persistent connection
for better performance.
-
Database connection, it
will
reconnect automaticallyimmediately
after disconnect. - Redis connection, it
won't
reconnect automaticallyimmediately
after disconnect, and will throw an exception about lost connection, reconnect next time. You need to make sure thatSELECT DB
correctly before operating Redis every time.
About memory leaks
-
Avoid using global variables. If necessary, please clean or reset them manually.
-
Infinitely appending element into
static
/global
variable will lead to OOM(Out of Memory). -
Memory leak detection method
-
Modify
config/laravels.php
:worker_num=1, max_request=1000000
, remember to change it back after test; -
Add routing
/debug-memory-leak
withoutroute middleware
to observe the memory changes of theWorker
process; -
Start
LaravelS
and request/debug-memory-leak
untildiff_mem
is less than or equal to zero; ifdiff_mem
is always greater than zero, it means that there may be a memory leak inGlobal Middleware
orLaravel Framework
; -
After completing
Step 3
,alternately
request the business routes and/debug-memory-leak
(It is recommended to useab
/wrk
to make a large number of requests for business routes), the initial increase in memory is normal. After a large number of requests for the business routes, ifdiff_mem
is always greater than zero andcurr_mem
continues to increase, there is a high probability of memory leak; Ifcurr_mem
always changes within a certain range and does not continue to increase, there is a low probability of memory leak. - If you still can't solve it, max_request is the last guarantee.
-
Linux kernel parameter adjustment
Pressure test
Alternatives
Sponsor
License
All versions of laravel-s with dependencies
ext-curl Version *
ext-json Version *
ext-pcntl Version *
swoole/ide-helper Version @dev
symfony/console Version >=6.4.0