Download the PHP package terranc/laravel-s without Composer
On this page you can find all versions of the php package terranc/laravel-s. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download terranc/laravel-s
More information about terranc/laravel-s
Files in terranc/laravel-s
Package laravel-s
Short Description π LaravelS is an out-of-the-box adapter between Swoole and Laravel/Lumen.
License MIT
Homepage https://github.com/terranc/laravel-s
Informations about the package laravel-s
π LaravelS is
an out-of-the-box adapterbetween Swoole and Laravel/Lumen.
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
- 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 | >= 5.5.9 Recommend PHP7+ |
| Swoole | >= 1.7.19 No longer support PHP5 since 2.0.12 Recommend 4.2.3+ |
| Laravel/Lumen | >= 5.1 Recommend 5.6+ |
Install
1.Require package via Composer(packagist).
2.Register service provider(pick one of two).
-
Laravel: inconfig/app.phpfile,Laravel 5.5+ supports package discovery automatically, you should skip this step Lumen: inbootstrap/app.phpfile
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 IOmode, so the larger theworker_numsetting, the better the concurrency performance, but it will also cause more memory usage and process switching overhead, so incremental pressure testing is needed to get 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
startandrestart.
| 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') |
Runtimefiles:startwill automatically executephp artisan laravels configand 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
-dand to setswoole.daemonizetofalse.
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/staticvariables, or change the currentRequest/Responseobject.
-
laravels.received_requestAfter LaravelS parsedSwoole\Http\RequesttoIlluminate\Http\Request, before Laravel's Kernel handles this request. laravels.generated_responseAfter Laravel's Kernel handled the request, before LaravelS parsesIlluminate\Http\ResponsetoSwoole\Http\Response.
Customized asynchronous events
This feature depends on
AsyncTaskofSwoole, your need to setswoole.task_worker_numinconfig/laravels.phpfirstly. 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
AsyncTaskofSwoole, your need to setswoole.task_worker_numinconfig/laravels.phpfirstly. 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
LinuxCrontab.
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
Linuxto 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 thatWorkerprocess 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
Sockethandler class, and extendHhxsv5\LaravelS\Swoole\Socket\{TcpSocket|UdpSocket|Http|WebSocket}.These
Socketconnections share the same worker processes with yourHTTP/WebSocketconnections. 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\Portobject directly by member propertyswoolePort. -
Register Sockets.
About the heartbeat configuration, it can only be set on the
main serverand cannot be configured onSocket, but theSocketinherits the heartbeat configuration of themain server.For TCP socket,
onConnectandonCloseevents will be blocked whendispatch_modeof Swoole is1/3, so if you want to unblock these two events please setdispatch_modeto2/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.enabletotrue.
-
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 NOTenable 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
LaravelSwill pull theApolloconfiguration and write it to the.envfile when starting. At the same time,LaravelSwill start the custom processapolloto monitor the configuration and automaticallyreloadwhen the configuration changes.
-
Enable Apollo: add
--enable-apolloand 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 |
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
XxxCleanerclass to clean up the singleton object state. This class implements the interfaceHhxsv5\LaravelS\Illuminate\Cleaners\CleanerInterfaceand then registers it incleanersoflaravels.php. -
Resetstatus of singleton instances byMiddleware. - Re-register
ServiceProvider, addXxxServiceProviderintoregister_providersof filelaravels.php. So that reinitialize singleton instances in every request Refer.
-
- LaravelS has built in some cleaners.
-
-
Known issues: a package of known issues and solutions.
-
Debugging method: Logging, Laravel Dump Server(Laravel 5.7 has been integrated by default).
-
Should get all request information from
Illuminate\Http\RequestObject, $_ENV is readable, $_SERVER is partially readable,CANNOT USE$_GET/$_POST/$_FILES/$_COOKIE/$_REQUEST/$_SESSION/$GLOBALS. -
Respond by
Illuminate\Http\ResponseObject, compatible with echo/vardump()/print_r()οΌCANNOT USEfunctions dd()/exit()/die()/header()/setcookie()/http_response_code(). - The various
singleton connectionswill bememory resident, recommend to enablepersistent connection.- Database connection, it
willreconnect automaticallyimmediatelyafter disconnect.
- Database connection, it
- Redis connection, it
won'treconnect automaticallyimmediatelyafter disconnect, and will throw an exception about lost connection, reconnect next time. You need to make sure thatSELECT DBcorrectly before operating Redis every time.
-
global,staticvariables which you declared are need to destroy(reset) manually. -
Infinitely appending element into
static/globalvariable will lead to OOM(Out of Memory). - 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 >=2.7.0