LoadBalancerManager.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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\LoadBalancer;
  12. use InvalidArgumentException;
  13. use function Hyperf\Support\make;
  14. class LoadBalancerManager
  15. {
  16. private array $algorithms = [
  17. 'random' => Random::class,
  18. 'round-robin' => RoundRobin::class,
  19. 'weighted-random' => WeightedRandom::class,
  20. 'weighted-round-robin' => WeightedRoundRobin::class,
  21. ];
  22. /**
  23. * @var LoadBalancerInterface[]
  24. */
  25. private array $instances = [];
  26. /**
  27. * Retrieve a class name of load balancer.
  28. */
  29. public function get(string $name): string
  30. {
  31. if (! $this->has($name)) {
  32. throw new InvalidArgumentException(sprintf('The %s algorithm does not exists.', $name));
  33. }
  34. return $this->algorithms[$name];
  35. }
  36. /**
  37. * Retrieve a class name of load balancer and create an object instance,
  38. * If $container object exists, then the class will create via container.
  39. *
  40. * @param string $key key of the load balancer instance
  41. * @param string $algorithm The name of the load balance algorithm
  42. */
  43. public function getInstance(string $key, string $algorithm): LoadBalancerInterface
  44. {
  45. if (isset($this->instances[$key])) {
  46. return $this->instances[$key];
  47. }
  48. $class = $this->get($algorithm);
  49. if (function_exists('Hyperf\Support\make')) {
  50. $instance = make($class);
  51. } else {
  52. $instance = new $class();
  53. }
  54. $this->instances[$key] = $instance;
  55. return $instance;
  56. }
  57. /**
  58. * Determine if the algorithm is exists.
  59. */
  60. public function has(string $name): bool
  61. {
  62. return isset($this->algorithms[$name]);
  63. }
  64. /**
  65. * Override the algorithms.
  66. */
  67. public function set(array $algorithms): static
  68. {
  69. foreach ($algorithms as $algorithm) {
  70. if (! class_exists($algorithm)) {
  71. throw new InvalidArgumentException(sprintf('The class of %s algorithm does not exists.', $algorithm));
  72. }
  73. }
  74. $this->algorithms = $algorithms;
  75. return $this;
  76. }
  77. /**
  78. * Register an algorithm to the manager.
  79. */
  80. public function register(string $key, string $algorithm): self
  81. {
  82. if (! class_exists($algorithm)) {
  83. throw new InvalidArgumentException(sprintf('The class of %s algorithm does not exists.', $algorithm));
  84. }
  85. $this->algorithms[$key] = $algorithm;
  86. return $this;
  87. }
  88. }