Swoole, php
git clone https://github.com/Watish/WatishWEBcomposer create-project watish/watishweb:dev-masterFile entri proyek adalah proyek /bin/coserver.php
swoole-cli ./bin/CoServer.php php ./bin/CoServer.php
Buat kelas baru di direktori src/controller , di sini kami mendefinisikannya sebagai hellocontroller
<?php
namespace Watish WatishWEB Controller ;
use Watish Components Attribute Path ;
use Watish Components Struct Request ;
class HelloController
{
#[Path( ' / ' )]
public function index ( Request $ request ) : array
{
return [
" msg " => " hello world "
];
}
}Setelah menabung, mulailah proyek dan kunjungi http://127.0.0.1:9502/ untuk melihat
{ "msg" : " hello world " }Bukankah itu sangat sederhana?
Berbeda dengan bentuk php-fpm tradisional, ada isolasi memori antara beberapa proses , yang berarti bahwa proses variabel B yang ditetapkan berdasarkan proses A tidak dapat diambil. Selain itu, permintaan tidak terisolasi . Dengan kata lain, dua permintaan dalam proses yang sama, meskipun logika pemrosesan dalam coroutine yang berbeda diproses, jika kedua variabel global A dimodifikasi, maka variabel global akan dimodifikasi dua kali.
Untuk detailnya, silakan merujuk ke instruksi pemrograman di Dokumen Sawo.
Gunakan komponen Watish termasuk konteks untuk secara efektif menghindari masalah di atas
Konteks adalah kelas statis yang tidak hanya menyediakan metode GET dan Set sederhana, tetapi juga menyediakan GlobalSet, GlobalGet, dan metode lain dari variabel global proses multi-pekerja melalui komunikasi proses.
CATATAN: Pengaturan variabel global proses multi-pekerja (konteks :: global_set, dll.) Diimplementasikan secara tidak sinkron berdasarkan Unixsocket. Itu tidak dapat menjamin konsistensi data pada saat tertentu. Di sini, Anda dapat menggunakan Watish Components utils Table , tabel memori KV yang dienkapsulasi untuk tabel swoole , yang dapat memanfaatkan sepenuhnya setiap baris sumber daya dan mendukung serialisasi penutupan.
Ketika browser mengirim permintaan ke server, server akan memanggil metode pegangan, dan kemudian menilai apakah rute yang diminta ada melalui penjadwal perutean. Parameter perutean ada, merangkumnya ke Watish Components struct request , dan meneruskannya ke middleware global-> middleware lokal-> controller
Dua cara untuk mendaftar perutean
Catatan: Anda perlu memodifikasi ** register_route_auto ** ke true di **/config/server.php **
. . .
" register_route_auto " => true
...Awalan adalah anotasi kelas yang mendefinisikan awalan rute di bawah kelas ini.
#[Prefix(string $ prefix )]Jalur adalah anotasi metode yang mendefinisikan jalur perutean
#[Path(string $ path ,array $ methods )]Ambil kastanye:
<?php
namespace Watish WatishWEB Controller ;
use Watish Components Attribute Middleware ;
use Watish Components Attribute Path ;
use Watish Components Attribute Prefix ;
use Watish Components Struct Request ;
use Watish WatishWEB Middleware TestMiddleware ;
#[Prefix( ' /hello ' )]
class HelloController
{
#[Path( ' /index ' )]
public function index ( Request $ request ) : array
{
return [
" msg " => " hello world "
];
}
#[Path( ' /user/{name} ' ,[ ' GET ' , ' POST ' ])]
#[Middleware([TestMiddleware::class])]
public function msg ( Request $ request ) : array
{
return [
" msg " => " hello " . $ request -> route ( ' name ' )
];
}
}Kode di atas dialihkan sebagai berikut
| jalur | Pengontrol | metode | middleware |
|---|---|---|---|
| /halo/indeks | HelloController@Index | SETIAP | tidak ada |
| /halo/user/{name} | HelloController@msg | Dapatkan, posting | Testmiddleware |
Jalur ke file konfigurasi routing adalah: Project/config/route.php
Gunakan kembali chestnut di atas, maka konfigurasi perutean di atas harus sebagai berikut
<?php
use Watish Components Includes Route ;
use Watish WatishWEB Controller HelloController ;
function do_register_global_middleware ( Route $ route ): void
{
/**
$route->register_global_middleware(CorsMiddleware::class);
*/
}
function do_register_routes ( Route $ route ): void
{
$ route -> register ( ' /hello/index ' ,[HelloController::class, ' index ' ],[],[]);
$ route -> register ( ' /hello/user/{name} ' ,[HelloController::class, ' msg ' ],[TestMiddleware: class ],[ ' GET ' , ' POST ' ]);
}Daftar Metode Parameter Transfer sebagai berikut
Watish Components Includes Route-> register (string $ path , array $ callback , array $ before_middlewares , array $ methods )Catatan: Middleware harus menerapkan antarmuka middleware
Daftar dengan anotasi
Anda dapat menerapkan pendaftaran middleware global dengan menggunakan anotasi kelas GlobalMiddleware
Misalnya:
<?php
namespace Watish WatishWEB Middleware ;
use Watish Components Attribute GlobalMiddleware ;
use Watish Components Struct Request ;
use Watish Components Struct Response ;
#[GlobalMiddleware]
class CorsMiddleware implements MiddlewareInterface
{
public function handle ( Request $ request , Response $ response ): void
{
$ response -> header ( " Access-Control-Allow-Origin " , " * " );
$ response -> header ( " Access-Control-Allow-Credentials " , true );
}
}Daftar melalui rute
Jalur file konfigurasi adalah: Project/config/route.php
<?php
use Watish Components Includes Route ;
use Watish WatishWEB Controller HelloController ;
use Watish WatishWEB Middleware CorsMiddleware ;
function do_register_global_middleware ( Route $ route ): void
{
$ route -> register_global_middleware (CorsMiddleware::class);
}
function do_register_routes ( Route $ route ): void
{
$ route -> register ( ' /hello/index ' ,[HelloController::class, ' index ' ],[],[]);
$ route -> register ( ' /hello/user/{name} ' ,[HelloController::class, ' msg ' ],[],[ ' GET ' , ' POST ' ]);
}Daftar dengan anotasi
Anda dapat menggunakan middleware untuk membuat anotasi pengontrol atau metode
#[Middleware(array $ middlewares )]Buat testmiddleware terlebih dahulu
<?php
namespace Watish WatishWEB Middleware ;
use Watish Components Struct Request ;
use Watish Components Struct Response ;
class TestMiddleware implements MiddlewareInterface
{
public function handle ( Request $ request , Response $ response )
{
$ response -> header ( " test " , " test " );
}
}Kemudian memodifikasi HelloController
<?php
namespace Watish WatishWEB Controller ;
use Watish Components Attribute Middleware ;
use Watish Components Attribute Path ;
use Watish Components Attribute Prefix ;
use Watish Components Struct Request ;
use Watish WatishWEB Middleware TestMiddleware ;
#[Prefix( ' /hello ' )]
class HelloController
{
#[Path( ' /index ' )]
#[Middleware([TestMiddleware::class])]
public function index ( Request $ request ) : array
{
return [
" msg " => " hello world "
];
}
#[Path( ' /user/{name} ' ,[ ' GET ' , ' POST ' ])]
#[Middleware([TestMiddleware::class])]
public function msg ( Request $ request ) : array
{
return [
" msg " => " hello " . $ request -> route ( ' name ' )
];
}
}Seperti disebutkan di atas, metode indeks dan metode MSG memiliki middleware testmiddle lokal
Tentu saja, kode di atas dapat ditulis seperti ini, dan langsung menambahkan anotasi middleware ke HelloController
<?php
namespace Watish WatishWEB Controller ;
use Watish Components Attribute Middleware ;
use Watish Components Attribute Path ;
use Watish Components Attribute Prefix ;
use Watish Components Struct Request ;
use Watish WatishWEB Middleware TestMiddleware ;
#[Prefix( ' /hello ' )]
#[Middleware([TestMiddleware::class])]
class HelloController
{
#[Path( ' /index ' )]
public function index ( Request $ request ) : array
{
return [
" msg " => " hello world "
];
}
#[Path( ' /user/{name} ' ,[ ' GET ' , ' POST ' ])]
public function msg ( Request $ request ) : array
{
return [
" msg " => " hello " . $ request -> route ( ' name ' )
];
}
}Daftar melalui file konfigurasi
Lihat Metode Pendaftaran Routing File Konfigurasi Dalam parameter Register Bagian Routing, bukan detail di sini
Pengontrol adalah inti dari seluruh proyek bisnis, yang bertanggung jawab untuk memproses permintaan, layanan panggilan, dan pengembalian data
Sederhana, tidak ada deskripsi
Bersama dengan injeksi ketergantungan , beri saya kastanye:
<?php
namespace Watish WatishWEB Controller ;
use Watish Components Attribute Inject ;
use Watish Components Attribute Middleware ;
use Watish Components Attribute Path ;
use Watish Components Attribute Prefix ;
use Watish Components Struct Request ;
use Watish WatishWEB Middleware TestMiddleware ;
use Watish WatishWEB Service BaseService ;
#[Prefix( ' /hello ' )]
#[Middleware([TestMiddleware::class])]
class HelloController
{
#[Inject(BaseService::class)]
public BaseService $ baseService ;
#[Path( ' /index ' )]
public function index ( Request $ request ) : array
{
return [
" msg " => $ this -> baseService -> toArray ([ " Hello " , ' World ' ])
];
}
#[Path( ' /user/{name} ' ,[ ' GET ' , ' POST ' ])]
public function msg ( Request $ request ) : array
{
return [
" msg " => " hello " . $ request -> route ( ' name ' )
];
}
}Catatan: Injeksi metode konstruksi tidak didukung untuk saat ini, dan itu akan ditingkatkan di masa depan (menggali lubang)
Kode Posting secara langsung
<?php
namespace Watish WatishWEB Service ;
use Watish Components Attribute Async ;
use Watish Components Attribute Inject ;
use Watish Components Utils Logger ;
class TestService
{
#[Inject(BaseService::class)]
public BaseService $ baseService ;
#[Async]
public function asyncHello (): void
{
Logger:: info ( " Hello " );
}
public function hello ( string $ name ) : string
{
return " hello { $ name }" ;
}
}Dalam layanan, injeksi ketergantungan masih dapat dilakukan. Selain itu, metode ini dapat beranotasi async (perhatikan bahwa metode yang dianotasi oleh async harus dari tipe void) untuk menjadikannya metode asinkron
File kelas perintah disimpan di Project/SRC/Command/
CATATAN: Kelas perintah memerlukan antarmuka CommandInterface implementasi
Kelas perintah hanya dapat mendaftarkan perintah menggunakan anotasi
Kode sampel adalah sebagai berikut:
<?php
namespace Watish WatishWEB Command ;
use Watish Components Attribute Command ;
use Watish Components Utils Logger ;
#[Command( " hello " , " command " )]
class HelloCommand implements CommandInterface
{
public function handle (): void
{
Logger:: info ( " Hello " );
}
}Kode di atas dapat dieksekusi dengan cara berikut
swoole-cli
swoole-cli ./bin/CoServer.php command:helloPhp
php ./bin/CoServer.php command:hello
Anotasi penggunaan perintah
Command (string $ command , string $ prefix = " command " )Kelas tugas disimpan dalam proyek/src/tugas/
Catatan: Semua kelas tugas perlu menerapkan TaskInterface
Kelas tugas hanya mendukung pendaftaran tugas -tugas waktunya menggunakan anotasi crontab .
Kode sampel adalah sebagai berikut:
<?php
namespace Watish WatishWEB Task ;
use Watish Components Attribute Crontab ;
use Watish Components Utils Logger ;
#[Crontab( " * * * * * " )]
class HelloTask implements TaskInterface
{
public function execute (): void
{
Logger:: info ( " Hello " , " HelloTask " );
}
}Ini adalah tugas waktunya yang menghasilkan halo setiap detik
Cara menggunakan anotasi crontab
Crontab (string $ rule )dimana aturan adalah ekspresi crontab standar
CATATAN: Hanya ada MySQL untuk saat ini, Redis (dapat menambahkannya sendiri)
Kerangka kerja ini menggunakan kumpulan koneksi untuk mempertahankan koneksi MySQL dan Redis, dan menyelesaikan pembuatan kumpulan koneksi di awal startup. Sekarang hanya perlu digunakan dalam logika bisnis.
** Watish Components termasuk database :: mysql () ** Mengembalikan enkapsulasi konstruktor kueri Laravel (terutama mengubah logika PDO yang mendasarinya, tidak ada perbedaan dalam penggunaan normal)
Watish Components termasuk database :: redis () mengembalikan klien predis
Harap konfigurasikan database terlebih dahulu! File Konfigurasi: Project/Config/Database.php
Kerangka kerja menggunakan komponen berikut dan merangkum beberapa komponen
Di bawah Watish Components Constructor Namespace, konstruksi cepat beberapa komponen disediakan
AsynctaskConstructor :: Make () Asynchronous Task Deliving
Localfilesystemconstructor :: getFilesystem () Local File System Constructor
ValidatorConstructor :: Make (array $ data, array $ aturan) Validator Constructor
Terima kasih kepada pengembang komponen yang sangat baik
Lingkungan Uji: Ubuntu22.0.4 LTS
Uji Perangkat Keras: Mesin Virtual (VirtualBox) 6C6T, 8192M, Aktifkan Dukungan Virtualisasi
Alat uji: ApacheBench
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
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)
Server Software: swoole-http-server
Server Hostname: 127.0.0.1
Server Port: 9502
Document Path: /hello/user/test
Document Length: 20 bytes
Concurrency Level: 3000
Time taken for tests: 2.040 seconds
Complete requests: 30000
Failed requests: 0
Total transferred: 7680000 bytes
HTML transferred: 600000 bytes
Requests per second: 14708.19 [#/sec] (mean)
Time per request: 203.968 [ms] (mean)
Time per request: 0.068 [ms] (mean, across all concurrent requests)
Transfer rate: 3677.05 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 83 17.3 85 125
Processing: 32 109 41.6 102 380
Waiting: 0 79 40.0 71 362
Total: 107 193 37.8 189 457
Percentage of the requests served within a certain time (ms)
50% 189
66% 200
75% 205
80% 208
90% 224
95% 236
98% 344
99% 389
100% 457 (longest request)
Catatan: Jangan terlalu memperhatikan kinerja. Logika bisnis yang sebenarnya seringkali rumit. Pengujian tekanan pada demo tidak dapat menunjukkan apa pun (gambar)
Jika mudah digunakan, Anda dapat mengklik bintang. Jika Anda memiliki pertanyaan, sebutkan masalahnya. Penulis akan secara aktif mempertahankannya.
Diperbarui pada 2022-12-28 16:01
Harap jalankan Instal Composer terlebih dahulu