/**
* 获取对象
*
* @param $serverId
* @param $workerId
* @return Client|false
*/
public static function getClient($serverGroup, $serverId, $workerId, $isTask = false)
{
if (!$serverGroup) {
# 服务器分组
$serverGroup = Server::$config['clusters']['group'] ?: 'default';
}
if ($isTask) {
$serverGroup .= '.task';
}
if (-1 === $serverId) {
# 随机服务器ID
$host = Host::getRandHostData($serverGroup);
if ($host) {
$serverId = $host['id'];
}
} else {
# 随机ID
$host = Host::$table->get("{$serverGroup}_{$serverId}");
}
if (!$host) {
return false;
}
if (-1 === $workerId) {
$workerId = mt_rand(0, $host['worker_num'] - 1);
}
# 生成一个KEY
$key = "{$serverGroup}_{$serverId}_{$workerId}";
if (!isset(self::$instances[$key])) {
if (!isset($host)) {
$host = Host::$table->get($serverId);
if (!$host) {
return false;
}
}
# 检查任务ID是否超出序号返回
if ($workerId - $host['worker_num'] > 1) {
return false;
}
/**
* @var Client $client
*/
$class = static::class;
$client = new $class();
$client->serverId = $serverId;
$client->workerId = $workerId;
$client->key = $host['key'];
$client->ip = $host['ip'];
$client->port = $host['port'];
$rs = $client->connect();
if (!$rs) {
# 没有连接上去
return false;
}
self::$instances[$key] = $client;
}
return self::$instances[$key];
}