Middleware.Class.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. namespace Jobs\Model;
  3. use Mall\Framework\Core\Config;
  4. use Mall\Framework\Core\ErrorCode;
  5. use Mall\Framework\Factory;
  6. class Middleware
  7. {
  8. static private $instance;
  9. private $resourceConfig;
  10. private $Swoole_Client;
  11. public function __construct($serviceName)
  12. {
  13. $this->resourceConfig = Config::getInstance()->get('dataResources');
  14. if (!empty($this->resourceConfig)) {
  15. $this->Swoole_Client = Factory::swoole($this->resourceConfig[$serviceName]);
  16. }
  17. }
  18. /**
  19. * 单例模式
  20. *
  21. * @param string $serviceName 服务名称
  22. *
  23. * @return object
  24. *
  25. * @throws \Exception
  26. */
  27. static public function getInstance($serviceName)
  28. {
  29. /*$serviceNameIndex = md5($serviceName);
  30. if (!isset(self::$instance[$serviceNameIndex])) {
  31. self::$instance[$serviceNameIndex] = new self($serviceName);
  32. }
  33. if (is_null(self::$instance[$serviceNameIndex]->resourceConfig)) {
  34. throw new \Exception('instance resourceConfig is null');
  35. }
  36. return self::$instance[$serviceNameIndex];*/
  37. return new self($serviceName);
  38. }
  39. /**
  40. * 发送swoole请求 目前统一封装为json消息体传输
  41. *
  42. * @param string $controller 控制器
  43. * @param string $action 方法
  44. * @param array $params 需要的参数
  45. *
  46. * @return mixed
  47. */
  48. public function sendSwoole($controller, $action, array $params = [])
  49. {
  50. //请求串号
  51. $serid = self::getRequestId();
  52. $msg = $this->structureMsg($controller, $action, $params, $serid);
  53. $result = $this->Swoole_Client->sendMsg($msg, $serid);
  54. if (!empty($result)) {
  55. return $result;
  56. } else {
  57. //todo 日志记录返回为空时得请求消息体
  58. return [
  59. 'state' => false,
  60. 'data' => 'swoole未返回消息',
  61. 'errorcode' => ErrorCode::$swooleRecvError
  62. ];
  63. }
  64. }
  65. /**
  66. * 生成请求串号
  67. * @return int
  68. */
  69. static function getRequestId()
  70. {
  71. $us = strstr(microtime(), ' ', true);
  72. return intval(strval($us * 1000 * 1000) . rand(100, 999));
  73. }
  74. /**
  75. * 构造发送消息体
  76. *
  77. * @param string $controller 控制器
  78. * @param string $action 方法
  79. * @param array $params 需要的参数
  80. * @param int $serid 请求串号
  81. *
  82. * @return string
  83. */
  84. private function structureMsg($controller, $action, $params = [], $serid, $uid = 0)
  85. {
  86. $data = json_encode([
  87. 'contorller' => ucfirst($controller),
  88. 'action' => $action,
  89. 'params' => $params
  90. ], JSON_UNESCAPED_UNICODE);
  91. return pack('NNN', strlen($data), $uid, $serid) . $data;
  92. }
  93. }