Swoole, Php
git clone https://github.com/Watish/WatishWEBcomposer create-project watish/watishweb:dev-master프로젝트의 입력 파일은 project /bin/coserver.php입니다
swoole-cli ./bin/CoServer.php php ./bin/CoServer.php
SRC/Controller 디렉토리에서 새 클래스를 작성하십시오. 여기서는 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 "
];
}
}저장 후 프로젝트를 시작하고 http://127.0.0.1:9502/
{ "msg" : " hello world " }매우 간단하지 않습니까?
기존 PHP-FPM 형태와 달리 여러 프로세스간에 메모리 분리가있어 프로세스 A에 의해 설정된 가변 프로세스 B를 검색 할 수 없습니다. 또한 요청이 격리되어 있지 않습니다 . 즉, 동일한 프로세스에서 두 개의 요청이지만, 다른 코 루틴의 처리 로직이 처리되지만, 글로벌 변수 A가 모두 수정되면 글로벌 변수는 두 번 수정됩니다.
자세한 내용은 Swoole 문서 #크리티컬 오류의 프로그래밍 지침을 참조하십시오.
위의 문제를 효과적으로 피하기 위해 Watish 구성 요소 포함 context를 사용하십시오
컨텍스트는 간단한 Get and Set 메소드를 제공 할뿐만 아니라 GlobalSet, GlobalGet 및 프로세스 커뮤니케이션을 통해 GlobalSet, GlobalGet 및 기타 다중 작업자 프로세스 방법을 제공하는 정적 클래스입니다.
참고 : 다중 작업자 프로세스 글로벌 변수 설정 (Context :: Global_set 등)은 UnixSocket을 기반으로 비동기식으로 구현됩니다. 특정 순간에 데이터의 일관성을 보장 할 수는 없습니다. 여기에서는 Swoole 테이블 의 캡슐화 된 KV 메모리 테이블 인 Watish Components Utils Table 을 사용할 수 있으며, 이는 각 자원 행을 최대한 활용하고 클로저 직렬화를 지원할 수 있습니다.
브라우저가 요청을 서버로 보내면 서버는 핸들 메소드를 호출 한 다음 라우팅 스케줄러를 통해 요청 된 경로가 존재하는지 판단합니다. 라우팅 매개 변수가 존재하고 Watish 구성 요소 struct request 로 캡슐화하여 글로벌 미들웨어-> 로컬 미들웨어-> 컨트롤러 로 전달합니다.
라우팅을 등록하는 두 가지 방법
참고 : **/config/server.php **에서 ** register_route_auto **를 true 로 수정해야합니다.
. . .
" register_route_auto " => true
...접두사 는이 클래스에서 경로의 접두사를 정의하는 클래스 주석 입니다.
#[Prefix(string $ prefix )]경로는 라우팅 경로를 정의하는 메소드 주석 입니다.
#[Path(string $ path ,array $ methods )]밤나무를 가져 가십시오 :
<?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 ' )
];
}
}위의 코드는 다음과 같이 라우팅됩니다
| 길 | 제어 장치 | 방법 | 미들웨어 |
|---|---|---|---|
| /hello/index | hellocontroller@index | 어느 | 없음 |
| /hello/user/{name} | hellocontroller@msg | 게시, 게시 | TestMiddleware |
라우팅 구성 파일의 경로는 다음과 같습니다. Project/Config/Route.php
위의 밤을 재사용하면 위의 라우팅 구성은 다음과 같습니다.
<?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 ' ]);
}다음과 같이 메소드 전송 매개 변수를 등록하십시오
Watish Components Includes Route-> register (string $ path , array $ callback , array $ before_middlewares , array $ methods )참고 : 미들웨어는 미들웨어 인터페이스를 구현해야합니다
주석으로 등록하십시오
GlobalMiddleware 클래스 주석을 사용하여 글로벌 미들웨어 등록을 구현할 수 있습니다.
예를 들어:
<?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 );
}
}경로를 통해 등록하십시오
구성 파일 경로는 다음과 같습니다. 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 ' ]);
}주석으로 등록하십시오
미들웨어를 사용하여 컨트롤러 또는 메소드 에 주석을 달 수 있습니다.
#[Middleware(array $ middlewares )]먼저 testmiddleware를 만듭니다
<?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 " );
}
}그런 다음 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 ' )
];
}
}위에서 언급했듯이 인덱스 방법과 MSG 방법에는 로컬 미들웨어 TestMiddleware 가 있습니다.
물론 위의 코드는 이렇게 작성할 수 있으며 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 ' )
];
}
}구성 파일을 통해 등록하십시오
라우팅 섹션 레지스터 매개 변수의 구성 파일 라우팅 등록 방법을 참조하십시오.
컨트롤러는 전체 비즈니스 프로젝트의 핵심이며 요청 처리, 서비스 호출 및 데이터 반환 데이터
간단하고 설명이 없습니다
의존성 주입 과 함께 밤나무를 줘 :
<?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 ' )
];
}
}참고 : 시공 방법 주입은 당분간 지원되지 않으며 향후 개선 될 것입니다 (구멍 파기).
우편 코드 직접
<?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 }" ;
}
}서비스 중에도 종속성 주입을 계속 수행 할 수 있습니다. 또한,이 방법은 비동기 방법으로 만들기 위해 비동기 주석을 달성 할 수 있습니다 (비동기로 주석이 공간 유형이어야 함).
명령 클래스 파일은 project/src/command/ 에 저장됩니다.
참고 : 명령 클래스에는 구현 명령 interface 인터페이스가 필요합니다
명령 클래스는 주석을 사용하여 명령 만 등록 할 수 있습니다
샘플 코드는 다음과 같습니다.
<?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 " );
}
}위의 코드는 다음 방법으로 실행할 수 있습니다.
Swoole-Cli
swoole-cli ./bin/CoServer.php command:helloPHP
php ./bin/CoServer.php command:hello
명령 사용에 대한 주석
Command (string $ command , string $ prefix = " command " )작업 클래스는 Project/SRC/Task/ 에 저장됩니다.
참고 : 모든 작업 클래스는 TaskInterface를 구현해야합니다
작업 클래스는 Crontab 주석을 사용하여 시간이 지정된 작업의 등록 만 지원합니다.
샘플 코드는 다음과 같습니다.
<?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 " );
}
}이것은 매 초마다 인사를 출력하는 시간이 지정된 작업입니다.
Crontab 주석을 사용하는 방법
Crontab (string $ rule )여기서 규칙은 표준 Crontab 표현식 입니다
참고 : 당분간 MySQL 만 있습니다. Redis (직접 추가 할 수 있음)
이 프레임 워크는 연결 풀을 사용하여 MySQL 및 Redis 연결을 유지하고 시작 시작시 연결 풀 생성을 완료합니다. 이제 비즈니스 로직에만 사용하면됩니다.
** watish components conture database :: mysql () ** Laravel 쿼리 생성자의 캡슐화를 반환합니다 (주로 기본 PDO 논리 변경, 정상 사용 차이 없음)
watish components conture database :: redis () predis 클라이언트를 반환합니다
먼저 데이터베이스를 구성하십시오! 구성 파일 : Project/Config/Database.php
프레임 워크는 다음 구성 요소를 사용하고 일부 구성 요소를 캡슐화합니다.
Watish 구성 요소 생성자 네임 스페이스에서 일부 구성 요소의 빠른 구성이 제공됩니다.
AsynctaskConstructor :: make () 비동기 작업 전달
localfilesystemconstructor :: getFilesystem () 로컬 파일 시스템 생성자
ValidatorConstructor :: make (배열 $ data, array $ rule) 유효성 생성기 생성자
훌륭한 구성 요소 개발자 덕분에
테스트 환경 : Ubuntu22.0.4 LT
테스트 하드웨어 : Virtual Machine (VirtualBox) 6C6T, 8192m, 가상화 지원 활성화
테스트 도구 : 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)
참고 : 성능에 너무 많은 관심을 기울이지 마십시오. 실제 비즈니스 논리는 종종 복잡합니다. 데모의 압력 테스트는 아무것도 표시 할 수 없습니다 (그림)
사용하기 쉬운 경우 별을 클릭 할 수 있습니다. 궁금한 점이 있으면 문제를 언급하십시오. 저자는 적극적으로 유지할 것입니다.
2022-12-28 16:01에 업데이트
먼저 작곡가 설치를 실행하십시오