服务端

独立使用代码

  1. <?php
  2. <?php
  3. /**
  4. * Created by PhpStorm.
  5. * User: xcg
  6. * Date: 2019/2/27
  7. * Time: 10:00
  8. */
  9. include_once dirname(__DIR__) . "/vendor/autoload.php";
  10. use EasySwoole\Rpc\Config;
  11. use EasySwoole\Rpc\Rpc;
  12. use EasySwoole\Rpc\Request;
  13. use EasySwoole\Rpc\Response;
  14. $config = new Config();
  15. //注册服务名称
  16. $config->setServiceName('ser1');
  17. //设置广播地址,可以多个地址
  18. $config->getAutoFindConfig()->setAutoFindBroadcastAddress(['127.0.0.1:9600']);
  19. //设置广播监听地址
  20. $config->getAutoFindConfig()->setAutoFindListenAddress('127.0.0.1:9600');
  21. //$config->setNodeManager(\EasySwoole\Rpc\NodeManager\TableManager::class);//设置节点管理器处理类,默认是EasySwoole\Rpc\NodeManager\FileManager
  22. $rpc = new Rpc($config);
  23. //注册响应方法
  24. $rpc->registerAction('call1', function (Request $request, Response $response) {
  25. //获取请求参数
  26. var_dump($request->getArg());
  27. //设置返回给客户端信息
  28. $response->setMessage('response');
  29. });
  30. //注册响应方法2
  31. $rpc->registerAction('call2', function (Request $request, Response $response)
  32. {});
  33. //监听/广播 rpc 自定义进程对象
  34. $autoFindProcess = $rpc->autoFindProcess('es_rpc_process_1');
  35. //创建第二个rpc服务
  36. $config2=new Config();
  37. $config2->setServiceName('ser2');
  38. $rpc2 = new Rpc($config2);
  39. //监听/广播 rpc 自定义进程对象
  40. $autoFindProcess2 = $rpc2->autoFindProcess('es_rpc_process_2');
  41. //创建http swoole服务
  42. $http = new swoole_http_server("127.0.0.1", 9525);
  43. //添加自定义进程到服务,开启进程
  44. $http->addProcess($autoFindProcess->getProcess());
  45. $http->addProcess($autoFindProcess2->getProcess());
  46. //rpc作为一个子服务运行
  47. $sub = $http->addlistener("127.0.0.1", 9527, SWOOLE_TCP);
  48. $sub2 = $http->addlistener("127.0.0.1", 9528, SWOOLE_TCP);
  49. //将swoole tcp子服务注入到rpc对象中,开始监听处理
  50. $rpc->attachToServer($sub);
  51. $rpc2->attachToServer($sub2);
  52. /**
  53. * http请求回调
  54. */
  55. $http->on("request", function ($request, $response) {
  56. $response->end("Hello World\n");
  57. });
  58. $http->start();
  59. ////rpc 作为主服务运行
  60. //$tcp = new swoole_server('127.0.0.1', 9526);
  61. //$tcp->addProcess($autoFindProcess->getProcess());
  62. //$rpc->attachToServer($tcp);
  63. //$tcp->start();