ReadyScheduler

Easyswoole 基础组件1.8.7版本起,提供了一个基于Swoole Table实现的就绪计划程序,用于解决主服务启动时,部分子服务未就绪问题。

基础测试使用

  1. namespace EasySwoole\Component\Tests;
  2. use EasySwoole\Component\ReadyScheduler;
  3. use PHPUnit\Framework\TestCase;
  4. use Swoole\Coroutine;
  5. class ReadySchedulerTest extends TestCase
  6. {
  7. function testNormal()
  8. {
  9. ReadyScheduler::getInstance()->addItem('worker');
  10. ReadyScheduler::getInstance()->addItem('rpc');
  11. ReadyScheduler::getInstance()->addItem('fastCache');
  12. go(function (){
  13. Coroutine::sleep(1);
  14. ReadyScheduler::getInstance()->ready('worker');
  15. ReadyScheduler::getInstance()->ready('rpc');
  16. });
  17. $this->assertEquals(false,ReadyScheduler::getInstance()->waitReady(['rpc','worker'],0.1));
  18. $this->assertEquals(true,ReadyScheduler::getInstance()->waitReady('rpc'));
  19. $this->assertEquals(true,ReadyScheduler::getInstance()->waitReady(['rpc','worker']));
  20. $this->assertEquals(false,ReadyScheduler::getInstance()->waitReady(['rpc','worker','fastCache'],1.1));
  21. }
  22. }

EasySwoole服务中使用

以Http服务作为基础例子

  1. namespace EasySwoole\EasySwoole;
  2. use EasySwoole\Component\ReadyScheduler;
  3. use EasySwoole\EasySwoole\Swoole\EventRegister;
  4. use EasySwoole\EasySwoole\AbstractInterface\Event;
  5. use EasySwoole\Http\Request;
  6. use EasySwoole\Http\Response;
  7. use Swoole\Coroutine;
  8. class EasySwooleEvent implements Event
  9. {
  10. public static function initialize()
  11. {
  12. // TODO: Implement initialize() method.
  13. date_default_timezone_set('Asia/Shanghai');
  14. }
  15. public static function mainServerCreate(EventRegister $register)
  16. {
  17. /*
  18. * 主进程初始化table
  19. */
  20. ReadyScheduler::getInstance();
  21. /*
  22. * 假设,服务启动的时候,依赖 serviceOne,serviceTwo 两个服务,例如链接第三方api等。
  23. * 在服务未就绪的时候,我们不希望本机器开始对外服务
  24. */
  25. $register->add($register::onWorkerStart,function ($serv, $workerId){
  26. if($workerId == 0){
  27. /*
  28. * 若不是强制准备,请注意addItem,unready,ready实现方法
  29. */
  30. Coroutine::sleep(3);
  31. ReadyScheduler::getInstance()->ready('serviceOne',true);
  32. var_dump('r1');
  33. }else if($workerId == 1){
  34. Coroutine::sleep(4);
  35. ReadyScheduler::getInstance()->ready('serviceTwo',true);
  36. var_dump('r2');
  37. }
  38. });
  39. }
  40. public static function onRequest(Request $request, Response $response): bool
  41. {
  42. /*
  43. * 链接进来的时候,判断依赖的服务是否就绪,等待时间为1s (tcp,ws服务也同理)
  44. * 在服务未就绪的时候,我们先拒绝服务
  45. */
  46. if(!ReadyScheduler::getInstance()->waitReady(['serviceOne','serviceTwo'],1.0)){
  47. $response->write('not ready,try again');
  48. return false;
  49. }
  50. return true;
  51. }
  52. public static function afterRequest(Request $request, Response $response): void
  53. {
  54. }
  55. }