RPCClient.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: liyunlong
  5. * Date: 2018-12-24
  6. * Time: 11:30
  7. */
  8. namespace common\libs\swoole;
  9. use yii\base\Exception;
  10. class RPCClient
  11. {
  12. const OK = 0;
  13. /**
  14. * 版本号
  15. */
  16. const VERSION = 1005;
  17. /**
  18. * Server的实例列表
  19. * @var array
  20. */
  21. protected $servers = array();
  22. protected $requestIndex = 0;
  23. protected $env = array();
  24. /**
  25. * 连接到服务器
  26. * @var array
  27. */
  28. protected $connections = array();
  29. protected $waitList = array();
  30. protected $timeout = 0.5;
  31. protected $packet_maxlen = 2097152; //最大不超过2M的数据包
  32. /**
  33. * 启用长连接
  34. * @var bool
  35. */
  36. protected $keepConnection = false;
  37. protected static $_instances = array();
  38. protected $encode_gzip = false;
  39. protected $encode_type = RPCServer::DECODE_PHP;
  40. protected $user;
  41. protected $password;
  42. private $keepSocket = false; //让整个对象保持同一个socket,不再重新分配
  43. private $keepSocketServer = array(); //对象保持同一个socket的服务器信息
  44. static $enableCoroutine = false;
  45. function __construct($id = null)
  46. {
  47. $key = empty($id) ? 'default' : $id;
  48. self::$_instances[$key] = $this;
  49. }
  50. /**
  51. * @param bool $keepSocket
  52. */
  53. public function setKeepSocket($keepSocket)
  54. {
  55. $this->keepSocket = $keepSocket;
  56. }
  57. /**
  58. * 设置编码类型
  59. * @param $type
  60. * @param $gzip
  61. * @throws \Exception
  62. */
  63. function setEncodeType($type, $gzip)
  64. {
  65. //兼容老版本,老版本true代表用json false代表serialize
  66. if ($type === true)
  67. {
  68. $type = RPCServer::DECODE_JSON;
  69. }
  70. if ($type === false)
  71. {
  72. $type = RPCServer::DECODE_PHP;
  73. }
  74. if ($type === RPCServer::DECODE_SWOOLE and (substr(PHP_VERSION, 0, 1) != '7'))
  75. {
  76. throw new \Exception("swoole_serialize only use in phpng");
  77. }
  78. else
  79. {
  80. $this->encode_type = $type;
  81. }
  82. if ($gzip)
  83. {
  84. $this->encode_gzip = true;
  85. }
  86. }
  87. /**
  88. * 获取SOA服务实例
  89. * @param $id
  90. * @return RPCClient
  91. */
  92. static function getInstance($id = null)
  93. {
  94. $key = empty($id) ? 'default' : $id;
  95. // if (self::$enableCoroutine)
  96. // {
  97. // return new self($id);
  98. // }
  99. if (empty(self::$_instances[$key]))
  100. {
  101. $object = new static($id);
  102. }
  103. else
  104. {
  105. $object = self::$_instances[$key];
  106. }
  107. return $object;
  108. }
  109. protected function beforeRequest($retObj)
  110. {
  111. }
  112. protected function afterRequest($retObj)
  113. {
  114. }
  115. /**
  116. * 生成请求串号
  117. * @return int
  118. */
  119. static function getRequestId()
  120. {
  121. $us = strstr(microtime(), ' ', true);
  122. return intval(strval($us * 1000 * 1000) . rand(100, 999));
  123. }
  124. protected function closeConnection($host, $port)
  125. {
  126. $conn_key = $host . ':' . $port;
  127. if (!isset($this->connections[$conn_key]))
  128. {
  129. return false;
  130. }
  131. $socket = $this->connections[$conn_key];
  132. $socket->close(true);
  133. unset($this->connections[$conn_key]);
  134. return true;
  135. }
  136. protected function getConnection($host, $port)
  137. {
  138. $ret = false;
  139. $conn_key = $host.':'.$port;
  140. if (isset($this->connections[$conn_key]))
  141. {
  142. return $this->connections[$conn_key];
  143. }
  144. //基于Swoole扩展
  145. $socket = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP, SWOOLE_SOCK_SYNC);
  146. $socket->set(array(
  147. 'open_length_check' => true,
  148. 'package_max_length' => $this->packet_maxlen,
  149. 'package_length_type' => 'N',
  150. 'package_body_offset' => RPCServer::HEADER_SIZE,
  151. 'package_length_offset' => 0,
  152. ));
  153. /**
  154. * 尝试重连一次
  155. */
  156. for ($i = 0; $i < 2; $i++)
  157. {
  158. $ret = $socket->connect($host, $port, $this->timeout);
  159. if ($ret === false and ($socket->errCode == 114 or $socket->errCode == 115))
  160. {
  161. //强制关闭,重连
  162. $socket->close(true);
  163. continue;
  164. }
  165. else
  166. {
  167. break;
  168. }
  169. }
  170. if ($ret)
  171. {
  172. $this->connections[$conn_key] = $socket;
  173. return $socket;
  174. }
  175. else
  176. {
  177. return false;
  178. }
  179. }
  180. /**
  181. * 验证缓存中是否存在已经配置为下线的连接 防止短时间内配置恢复后连接错误使用
  182. * @param $servers
  183. */
  184. protected function validConnection($servers)
  185. {
  186. $offline = [];
  187. foreach ($servers as $k => $svr)
  188. {
  189. if (!empty($svr['status']) and $svr['status'] == 'offline')
  190. {
  191. $offline[] = $svr;
  192. }
  193. }
  194. if (!empty($offline)) {
  195. foreach ($offline as $svr)
  196. {
  197. $conn_key = $svr['host'].':'.$svr['port'];
  198. if (isset($this->connections[$conn_key]))
  199. {
  200. $socket = $this->connections[$conn_key];
  201. $socket->close(true);
  202. unset($this->connections[$conn_key]);
  203. }
  204. }
  205. }
  206. }
  207. /**
  208. * 连接到服务器
  209. * @param $retObj
  210. * @return bool
  211. * @throws Exception
  212. */
  213. protected function connectToServer($retObj)
  214. {
  215. $servers = $this->servers;
  216. //循环连接
  217. while (count($servers) > 0)
  218. {
  219. $svr = $this->getServer($servers);
  220. if (empty($svr))
  221. {
  222. return false;
  223. }
  224. $this->validConnection($servers);
  225. $socket = $this->getConnection($svr['host'], $svr['port']);
  226. //连接失败,服务器节点不可用
  227. //TODO 如果连接失败,需要上报机器存活状态
  228. if ($socket === false)
  229. {
  230. foreach($servers as $k => $v)
  231. {
  232. if ($v['host'] == $svr['host'] and $v['port'] == $svr['port'])
  233. {
  234. //从Server列表中移除
  235. unset($servers[$k]);
  236. }
  237. }
  238. if ($this->keepSocket)
  239. {
  240. //若连接失败,则清除掉该server
  241. $this->keepSocketServer = array();
  242. }
  243. }
  244. else
  245. {
  246. $retObj->socket = $socket;
  247. $retObj->server_host = $svr['host'];
  248. $retObj->server_port = $svr['port'];
  249. return true;
  250. }
  251. }
  252. return false;
  253. }
  254. /**
  255. * RPCResult
  256. * @param $send
  257. * @param RPCResult $retObj
  258. * @return bool
  259. * @throws Exception
  260. */
  261. protected function request($send, RPCResult $retObj)
  262. {
  263. $retObj->send = $send;
  264. $this->beforeRequest($retObj);
  265. $retObj->index = $this->requestIndex++;
  266. connect_to_server:
  267. if ($this->connectToServer($retObj) === false)
  268. {
  269. $retObj->code = RPCResult::ERR_CONNECT;
  270. return false;
  271. }
  272. //请求串号
  273. $retObj->requestId = self::getRequestId();
  274. //打包格式
  275. $encodeType = $this->encode_type;
  276. if ($this->encode_gzip)
  277. {
  278. $encodeType |= RPCServer::DECODE_GZIP;
  279. }
  280. //发送失败了
  281. if ($retObj->socket->send(RPCServer::encode($retObj->send, $encodeType, 0, $retObj->requestId)) === false)
  282. {
  283. $this->closeConnection($retObj->server_host, $retObj->server_port);
  284. //连接被重置了,重现连接到服务器
  285. if ($retObj->socket->errCode == 104)
  286. {
  287. goto connect_to_server;
  288. }
  289. $retObj->code = RPCResult::ERR_SEND;
  290. unset($retObj->socket);
  291. return false;
  292. }
  293. $retObj->code = RPCResult::ERR_RECV;
  294. //加入wait_list
  295. $this->waitList[$retObj->requestId] = $retObj;
  296. return true;
  297. }
  298. /**
  299. * 设置环境变量
  300. * @return array
  301. */
  302. public function getEnv()
  303. {
  304. return $this->env;
  305. }
  306. /**
  307. * 获取环境变量
  308. * @param array $env
  309. */
  310. public function setEnv($env)
  311. {
  312. $this->env = $env;
  313. }
  314. /**
  315. * 设置一项环境变量
  316. * @param $k
  317. * @param $v
  318. */
  319. public function putEnv($k, $v)
  320. {
  321. $this->env[$k] = $v;
  322. }
  323. /**
  324. * 设置超时时间,包括连接超时和接收超时
  325. * @param $timeout
  326. */
  327. public function setTimeout($timeout)
  328. {
  329. $this->timeout = $timeout;
  330. }
  331. /**
  332. * 设置用户名和密码
  333. * @param $user
  334. * @param $password
  335. */
  336. public function auth($user, $password)
  337. {
  338. $this->putEnv('user', $user);
  339. $this->putEnv('password', $password);
  340. }
  341. /**
  342. * 完成请求
  343. * @param $retData
  344. * @param $retObj RPCResult
  345. */
  346. protected function finish($retData, $retObj)
  347. {
  348. //解包失败了
  349. if ($retData === false)
  350. {
  351. $retObj->code = RPCResult::ERR_UNPACK;
  352. }
  353. //调用成功
  354. elseif ($retData['errno'] === self::OK)
  355. {
  356. $retObj->code = self::OK;
  357. $retObj->data = $retData['data'];
  358. $retObj->msg = null;
  359. }
  360. //服务器返回失败
  361. else
  362. {
  363. $retObj->code = $retData['errno'];
  364. $retObj->data = null;
  365. $retObj->msg = $retData['msg'];
  366. }
  367. unset($this->waitList[$retObj->requestId]);
  368. //执行after钩子函数
  369. $this->afterRequest($retObj);
  370. //执行回调函数
  371. if ($retObj->callback)
  372. {
  373. call_user_func($retObj->callback, $retObj);
  374. }
  375. }
  376. /**
  377. * 添加服务器
  378. * @param array $servers
  379. * @throws Exception
  380. */
  381. public function addServers(array $servers)
  382. {
  383. if (isset($servers['host']))
  384. {
  385. self::formatServerConfig($servers);
  386. $this->servers[] = $servers;
  387. }
  388. else
  389. {
  390. //兼容老的写法
  391. foreach ($servers as $svr)
  392. {
  393. // 127.0.0.1:8001 的写法
  394. if (is_string($svr))
  395. {
  396. list($config['host'], $config['port']) = explode(':', $svr);
  397. }
  398. else
  399. {
  400. $config = $svr;
  401. }
  402. self::formatServerConfig($config);
  403. $this->servers[] = $config;
  404. }
  405. }
  406. }
  407. /**
  408. * @param $config
  409. * @throws Exception
  410. */
  411. static protected function formatServerConfig(&$config)
  412. {
  413. if (empty($config['host']))
  414. {
  415. throw new Exception("require 'host' option.");
  416. }
  417. if (empty($config['port']))
  418. {
  419. throw new Exception("require 'port' option.");
  420. }
  421. if (empty($config['status']))
  422. {
  423. $config['status'] = 'online';
  424. }
  425. if (empty($config['weight']))
  426. {
  427. $config['weight'] = 100;
  428. }
  429. }
  430. /**
  431. * 设置服务器
  432. * @param array $servers
  433. * @throws Exception
  434. */
  435. public function setServers(array $servers)
  436. {
  437. foreach($servers as &$svr)
  438. {
  439. self::formatServerConfig($svr);
  440. }
  441. $this->servers = $servers;
  442. }
  443. /**
  444. * 从配置中取出一个服务器配置
  445. * @param $servers
  446. * @return array|mixed
  447. * @throws Exception
  448. */
  449. public function getServer($servers)
  450. {
  451. if (empty($servers))
  452. {
  453. throw new Exception("servers config empty.");
  454. }
  455. if ($this->keepSocket)
  456. {
  457. if (is_array($this->keepSocketServer) && count($this->keepSocketServer))
  458. {
  459. return $this->keepSocketServer;
  460. }
  461. else
  462. {
  463. $this->keepSocketServer = self::toolGetServer($servers);
  464. return $this->keepSocketServer;
  465. }
  466. }
  467. //保留老的server获取方式
  468. return self::toolGetServer($servers);
  469. }
  470. /**
  471. * RPC调用
  472. * @param $function
  473. * @param array $params
  474. * @param null $callback
  475. * @return RPCResult
  476. * @throws Exception
  477. */
  478. public function task($function, $params = array(), $callback = null)
  479. {
  480. $retObj = new RPCResult($this);
  481. $send = array('call' => $function, 'params' => $params);
  482. if (count($this->env) > 0)
  483. {
  484. //调用端环境变量
  485. $send['env'] = $this->env;
  486. }
  487. $this->request($send, $retObj);
  488. $retObj->callback = $callback;
  489. return $retObj;
  490. }
  491. /**
  492. * 侦测服务器是否存活
  493. * @return bool
  494. * @throws \Exception
  495. */
  496. public function ping()
  497. {
  498. return $this->task('PING')->getResult() === 'PONG';
  499. }
  500. /**
  501. * @param $connection
  502. * @param float $timeout
  503. * @return bool|string
  504. */
  505. protected function recvPacket($connection, $timeout=0.5)
  506. {
  507. return $connection->recv();
  508. }
  509. /**
  510. * select等待数据接收事件
  511. * @param $read
  512. * @param $write
  513. * @param $error
  514. * @param $timeout
  515. * @return int
  516. */
  517. protected function select($read, $write, $error, $timeout)
  518. {
  519. return swoole_client_select($read, $write, $error, $timeout);
  520. }
  521. protected function freeConnection($socket)
  522. {
  523. }
  524. /**
  525. * 接收响应
  526. * @param $timeout
  527. * @return int
  528. */
  529. public function wait($timeout = 0.5)
  530. {
  531. $st = microtime(true);
  532. $success_num = 0;
  533. $read = [];
  534. while (count($this->waitList) > 0)
  535. {
  536. $write = $error = array();
  537. foreach ($this->waitList as $obj)
  538. {
  539. /**
  540. * @var $obj RPCResult
  541. */
  542. if ($obj->socket !== null)
  543. {
  544. $read[] = $obj->socket;
  545. }
  546. }
  547. if (empty($read))
  548. {
  549. break;
  550. }
  551. //去掉重复的socket
  552. self::arrayUnique($read);
  553. //等待可读事件
  554. $n = $this->select($read, $write, $error, $timeout);
  555. if ($n > 0)
  556. {
  557. //可读
  558. foreach($read as $connection)
  559. {
  560. $data = $this->recvPacket($connection,$timeout);
  561. //socket被关闭了
  562. if ($data === "")
  563. {
  564. foreach($this->waitList as $retObj)
  565. {
  566. if ($retObj->socket == $connection)
  567. {
  568. $retObj->code = RPCResult::ERR_CLOSED;
  569. unset($this->waitList[$retObj->requestId]);
  570. $this->closeConnection($retObj->server_host, $retObj->server_port);
  571. //执行after钩子函数
  572. $this->afterRequest($retObj);
  573. }
  574. }
  575. continue;
  576. }
  577. elseif ($data === false)
  578. {
  579. continue;
  580. }
  581. $header = unpack(RPCServer::HEADER_STRUCT, substr($data, 0, RPCServer::HEADER_SIZE));
  582. //不在请求列表中,错误的请求串号
  583. if (!isset($this->waitList[$header['serid']]))
  584. {
  585. trigger_error(__CLASS__ . " invalid responseId[{$header['serid']}].", E_USER_WARNING);
  586. continue;
  587. }
  588. $retObj = $this->waitList[$header['serid']];
  589. //成功处理
  590. $this->finish(RPCServer::decode(substr($data, RPCServer::HEADER_SIZE), $header['type']), $retObj);
  591. $success_num++;
  592. }
  593. }
  594. //发生超时
  595. if ((microtime(true) - $st) > $timeout)
  596. {
  597. foreach ($this->waitList as $obj)
  598. {
  599. $obj->code = ($obj->socket->isConnected()) ? RPCResult::ERR_TIMEOUT : RPCResult::ERR_CONNECT;
  600. $this->closeConnection($obj->server_host, $obj->server_port);
  601. //执行after钩子函数
  602. $this->afterRequest($obj);
  603. }
  604. //清空当前列表
  605. $this->waitList = array();
  606. foreach($read as $r)
  607. {
  608. $this->freeConnection($r);
  609. }
  610. return $success_num;
  611. }
  612. }
  613. foreach($read as $r)
  614. {
  615. $this->freeConnection($r);
  616. }
  617. //未发生任何超时
  618. $this->waitList = array();
  619. $this->requestIndex = 0;
  620. return $success_num;
  621. }
  622. /**
  623. * 关闭所有连接
  624. */
  625. public function close()
  626. {
  627. foreach ($this->connections as $key => $socket)
  628. {
  629. /**
  630. * @var $socket \swoole_client
  631. */
  632. $socket->close(true);
  633. unset($this->connections[$key]);
  634. }
  635. }
  636. /**
  637. * @param array $servers
  638. * @return mixed
  639. */
  640. public static function toolGetServer(array $servers)
  641. {
  642. $weight = 0;
  643. //移除不在线的节点
  644. foreach ($servers as $k => $svr)
  645. {
  646. //节点已掉线
  647. if (!empty($svr['status']) and $svr['status'] == 'offline')
  648. {
  649. unset($servers[$k]);
  650. }
  651. else
  652. {
  653. $weight += $svr['weight'];
  654. }
  655. }
  656. //计算权重并随机选择一台机器
  657. $use = rand(0, $weight - 1);
  658. $weight = 0;
  659. foreach ($servers as $k => $svr)
  660. {
  661. //默认100权重
  662. if (empty($svr['weight']))
  663. {
  664. $svr['weight'] = 100;
  665. }
  666. $weight += $svr['weight'];
  667. //在权重范围内
  668. if ($use < $weight)
  669. {
  670. return $svr;
  671. }
  672. }
  673. //绝不会到这里
  674. $servers = array_values($servers);
  675. return $servers[0];
  676. }
  677. /**
  678. * 数组去重
  679. * @param array $arr
  680. */
  681. public static function arrayUnique(array &$arr)
  682. {
  683. $map = array();
  684. foreach ($arr as $k => $v)
  685. {
  686. if (is_object($v))
  687. {
  688. $hash = spl_object_hash($v);
  689. }
  690. elseif (is_resource($v))
  691. {
  692. $hash = intval($v);
  693. }
  694. else
  695. {
  696. $hash = $v;
  697. }
  698. if (isset($map[$hash]))
  699. {
  700. unset($arr[$k]);
  701. }
  702. else
  703. {
  704. $map[$hash] = true;
  705. }
  706. }
  707. }
  708. }