ServiceInfo.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Nacos\Protobuf;
  12. use Hyperf\Contract\JsonDeSerializable;
  13. use JsonSerializable;
  14. class ServiceInfo implements JsonDeSerializable, JsonSerializable
  15. {
  16. /**
  17. * @param ServiceHost[] $hosts
  18. */
  19. public function __construct(
  20. public string $name,
  21. public string $groupName,
  22. public string $clusters,
  23. public int $cacheMillis = 0,
  24. public array $hosts = [],
  25. public int $lastRefTime = 0,
  26. public string $checksum = '',
  27. public bool $allIPs = false,
  28. public bool $reachProtectionThreshold = false,
  29. public bool $valid = false,
  30. ) {
  31. }
  32. public static function jsonDeSerialize(mixed $data): static
  33. {
  34. $hosts = [];
  35. foreach ($data['hosts'] ?? [] as $host) {
  36. $hosts[] = ServiceHost::jsonDeSerialize($host);
  37. }
  38. return new static(
  39. $data['name'],
  40. $data['groupName'],
  41. $data['clusters'],
  42. $data['cacheMillis'],
  43. $hosts,
  44. $data['lastRefTime'],
  45. $data['checksum'],
  46. $data['allIPs'],
  47. $data['reachProtectionThreshold'],
  48. $data['valid'],
  49. );
  50. }
  51. public function jsonSerialize(): mixed
  52. {
  53. return [
  54. 'name' => $this->name,
  55. 'groupName' => $this->groupName,
  56. 'clusters' => $this->clusters,
  57. 'cacheMillis' => $this->cacheMillis,
  58. 'hosts' => $this->hosts,
  59. 'lastRefTime' => $this->lastRefTime,
  60. 'checksum' => $this->checksum,
  61. 'allIPs' => $this->allIPs,
  62. 'reachProtectionThreshold' => $this->reachProtectionThreshold,
  63. 'valid' => $this->valid,
  64. ];
  65. }
  66. public function toKeyString(): string
  67. {
  68. return self::getKeyString($this->clusters, $this->groupName, $this->name);
  69. }
  70. public static function getKeyString(string $clusters, string $group, string $service): string
  71. {
  72. return sprintf('%s#%s@@%s', $clusters, $group, $service);
  73. }
  74. }