Marco de microservicios PHP - Publicación de Swoft 2.0.3

imagen


¿Qué es swoft?


Swoft es un marco de trabajo de microservicios PHP basado en la extensión Swoole . Al igual que Go, Swoft tiene un servidor web de rutina incorporado y un cliente de rutina común y es residente en la memoria, independiente del PHP-FPM tradicional. Existen operaciones similares del lenguaje Go, similares a las anotaciones flexibles del marco de Spring Cloud, un poderoso contenedor de inyección de dependencia global, un gobierno de servicio integral, AOP flexible y potente, implementación de especificación de PSR estándar, etc.


A través de tres años de acumulación y exploración de direcciones, Swoft ha convertido a Swoft en la Nube de Primavera en el mundo PHP, que es la mejor opción para el marco de trabajo de alto rendimiento y la gestión de microservicios de PHP.


Gobierno de servicio elegante


Swoft recomienda oficialmente que los desarrolladores utilicen patrones de malla de servicios, como el marco Istio / Envoy, para separar la gobernanza empresarial y de servicios, pero Swoft también proporciona un conjunto de componentes de microservicios para que las pequeñas y medianas empresas creen microservicios rápidamente.



Servicio de registro y descubrimiento


Para el registro y descubrimiento del servicio, se requiere el componente swoft-consul provisto por Swoft, si otros terceros son similares.


Servicios de registro y cancelación.


Escuche el evento SwooleEvent::START , registre el servicio


 /** * Class RegisterServiceListener * * @since 2.0 * * @Listener(event=SwooleEvent::START) */ class RegisterServiceListener implements EventHandlerInterface { /** * @Inject() * * @var Agent */ private $agent; /** * @param EventInterface $event */ public function handle(EventInterface $event): void { /* @var HttpServer $httpServer */ $httpServer = $event->getTarget(); $service = [ // .... ]; $scheduler = Swoole\Coroutine\Scheduler(); $scheduler->add(function () use ($service) { // Register $this->agent->registerService($service); CLog::info('Swoft http register service success by consul!'); }); $scheduler->start(); } } 

Escuche el evento SwooleEvent::SHUTDOWN , cancele el servicio


 /** * Class DeregisterServiceListener * * @since 2.0 * * @Listener(SwooleEvent::SHUTDOWN) */ class DeregisterServiceListener implements EventHandlerInterface { /** * @Inject() * * @var Agent */ private $agent; /** * @param EventInterface $event */ public function handle(EventInterface $event): void { /* @var HttpServer $httpServer */ $httpServer = $event->getTarget(); $scheduler = Swoole\Coroutine\Scheduler(); $scheduler->add(function () use ($httpServer) { $this->agent->deregisterService('swoft'); }); $scheduler->start(); } } 

Descubrimiento de servicio


Definiendo un proveedor de servicios


 /** * Class RpcProvider * * @since 2.0 * * @Bean() */ class RpcProvider implements ProviderInterface { /** * @Inject() * * @var Agent */ private $agent; /** * @param Client $client * * @return array * @example * [ * 'host:port' * ] */ public function getList(Client $client): array { // Get health service from consul $services = $this->agent->services(); $services = [ ]; return $services; } } 

Proveedor de servicios de configuración


 return [ 'user' => [ 'class' => ServiceClient::class, 'provider' => bean(RpcProvider::class) // ... ] ]; 

Interruptor de servicio


Swoft usa la anotación @Breaker para lograr un golpe, que se puede volar en cualquier método.


 /** * Class BreakerLogic * * @since 2.0 * * @Bean() */ class BreakerLogic { /** * @Breaker(fallback="funcFallback") * * @return string * @throws Exception */ public function func(): string { // Do something throw new Exception('Breaker exception'); } /** * @return string */ public function funcFallback(): string { return 'funcFallback'; } } 

Límite de servicio


Swoft usa la anotación @RateLimiter para implementar la @RateLimiter servicio, que puede limitarse en cualquier método, no solo en el controlador, y KEY también admite el lenguaje de expresión de lenguaje de expresiones / symfony .


 /** * Class LimiterController * * @since 2.0 * * @Controller(prefix="limiter") */ class LimiterController { /** * @RequestMapping() * @RateLimiter(key="request.getUriPath()", fallback="limiterFallback") * * @param Request $request * * @return array */ public function requestLimiter(Request $request): array { $uri = $request->getUriPath(); return ['requestLimiter', $uri]; } /** * @param Request $request * * @return array */ public function limiterFallback(Request $request): array { $uri = $request->getUriPath(); return ['limiterFallback', $uri]; } } 

Centro de configuración


El centro de configuración debe usar el componente Swoft-apollo proporcionado por Swoft oficialmente, si otros terceros son similares.


Declarar agente


 /** * Class AgentCommand * * @since 2.0 * * @Command("agent") */ class AgentCommand { /** * @Inject() * * @var Config */ private $config; /** * @CommandMapping(name="index") */ public function index(): void { $namespaces = [ 'application' ]; while (true) { try { $this->config->listen($namespaces, [$this, 'updateConfigFile']); } catch (Throwable $e) { CLog::error('Config agent fail(%s %s %d)!', $e->getMessage(), $e->getFile(), $e->getLine()); } } } /** * @param array $data * * @throws ContainerException * @throws ReflectionException */ public function updateConfigFile(array $data): void { foreach ($data as $namespace => $namespaceData) { $configFile = sprintf('@config/%s.php', $namespace); $configKVs = $namespaceData['configurations'] ?? ''; $content = '<?php return ' . var_export($configKVs, true) . ';'; Co::writeFile(alias($configFile), $content, FILE_NO_DEFAULT_CONTEXT); CLog::info('Apollo update success!'); /** @var HttpServer $server */ $server = bean('httpServer'); $server->restart(); } } } 

Agente de inicio


El Agente solo necesita ejecutarse antes de que se inicie el servicio (Http / RPC / Websocket).


 php bin/swoft agent:index 

Recurso


Source: https://habr.com/ru/post/460147/


All Articles