
斯沃夫特是什么?
Swoft是一个基于Swoole扩展的PHP微服务协同程序框架。 像Go一样,Swoft具有内置的协程Web服务器和通用的协程客户端,并且驻留在内存中,而与传统的PHP-FPM无关。 有类似的Go语言操作,类似于Spring Cloud框架的灵活注释,强大的全局依赖项注入容器,全面的服务治理,灵活而强大的AOP,标准PSR规范实现等。
通过三年的积累和方向探索,Swoft使Swoft成为了PHP世界中的Spring Cloud,它是PHP高性能框架和微服务管理的最佳选择。
优雅的服务治理
Swoft正式建议开发人员使用服务网格模式(例如Istio / Envoy框架)来分离业务和服务管理,但是Swoft还为中小型企业提供了一组微服务组件,以快速构建微服务。
服务注册和发现
对于服务注册和发现,如果其他第三方相似,则需要由Swoft提供的swoft-consul组件。
注册和取消服务
监听SwooleEvent::START
事件,注册服务
class RegisterServiceListener implements EventHandlerInterface { private $agent; public function handle(EventInterface $event): void { $httpServer = $event->getTarget(); $service = [
侦听SwooleEvent::SHUTDOWN
事件,取消服务
class DeregisterServiceListener implements EventHandlerInterface { private $agent; public function handle(EventInterface $event): void { $httpServer = $event->getTarget(); $scheduler = Swoole\Coroutine\Scheduler(); $scheduler->add(function () use ($httpServer) { $this->agent->deregisterService('swoft'); }); $scheduler->start(); } }
服务发现
定义服务提供商
class RpcProvider implements ProviderInterface { private $agent; public function getList(Client $client): array {
配置服务提供商
return [ 'user' => [ 'class' => ServiceClient::class, 'provider' => bean(RpcProvider::class)
服务断路器
Swoft使用@Breaker
批注来实现打击,可以使用任何方法对其进行打击。
class BreakerLogic { public function func(): string {
服务限额
Swoft使用@RateLimiter
批注实现服务限制,可以在任何方法上限制它,而不仅仅是控制器,并且KEY还支持symfony /表达式语言表达语言。
class LimiterController { public function requestLimiter(Request $request): array { $uri = $request->getUriPath(); return ['requestLimiter', $uri]; } public function limiterFallback(Request $request): array { $uri = $request->getUriPath(); return ['limiterFallback', $uri]; } }
配置中心
如果其他第三方相似,则配置中心需要使用Swoft正式提供的Swoft-apollo组件。
申报代理
class AgentCommand { private $config; 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()); } } } 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!'); $server = bean('httpServer'); $server->restart(); } } }
启动代理
代理仅需要在启动服务(Http / RPC / Websocket)之前运行。
php bin/swoft agent:index
资源资源