diff --git a/src/Client.php b/src/Client.php index 02a3d3d..48e715f 100644 --- a/src/Client.php +++ b/src/Client.php @@ -46,6 +46,13 @@ class Client */ protected $cluster; + /** + * Tells client to send queries over whole cluster selecting server by random + * + * @var bool + */ + protected $useRandomServer = false; + /** * Client constructor. * @@ -77,6 +84,26 @@ public function __construct($server, QueryMapperInterface $mapper = null, Transp $this->setMapper($mapper); } + /** + * Sets flag to use random server in cluster + * + * @param bool $flag + */ + public function useRandomServer(bool $flag) + { + $this->useRandomServer = $flag; + } + + /** + * Returns flag which tells client to use random server in cluster + * + * @return bool + */ + protected function shouldUseRandomServer() : bool + { + return !is_null($this->getCluster()) && $this->useRandomServer; + } + /** * Creates default http transport. * @@ -162,9 +189,29 @@ public function setServer(Server $server): self */ public function getServer(): Server { + if ($this->shouldUseRandomServer()) { + return $this->getRandomServer(); + } + return $this->server; } + /** + * Returns random server from cluster + * + * @return \Tinderbox\Clickhouse\Server + */ + public function getRandomServer() : Server + { + $cluster = $this->getCluster(); + $servers = $cluster->getServers(); + $random = array_rand($servers, 1); + + dump($servers[$random]); + + return $servers[$random]; + } + /** * Sets cluster. *