目前有多个使用Gateway的项目,这几个项目都是通过自己开发的中间件来互相转发消息,今晚发现,使用GatewatClient时,在同一个中间件同时发送消息给多个项目时(也就是有多个注册中心地址$registerAddress),始终只能发送到第一个$registerAddress,大致看了下源码,貌似是
getAllGatewayAddressesFromRegister 这个方法在作怪?有个临时的静态变量 $addresses_cache 缓存了注册中心地址:
/**
* 获取通过注册中心获取所有 gateway 通讯地址
*
* @return array
* @throws Exception
*/
protected static function getAllGatewayAddressesFromRegister()
{
static $addresses_cache, $last_update;
$time_now = time();
$expiration_time = 1;
if(empty($addresses_cache) || $time_now - $last_update > $expiration_time) {
$client = stream_socket_client('tcp://' . self::$registerAddress, $errno, $errmsg, self::$connectTimeout);
if (!$client) {
throw new Exception('Can not connect to tcp://' . self::$registerAddress . ' ' . $errmsg);
}
fwrite($client, '{"event":"worker_connect","secret_key":"' . self::$secretKey . '"}' . "\n");
stream_set_timeout($client, 1);
$ret = fgets($client, 655350);
if (!$ret || !$data = json_decode(trim($ret), true)) {
throw new Exception('getAllGatewayAddressesFromRegister fail. tcp://' .
self::$registerAddress . ' return ' . var_export($ret, true));
}
$last_update = $time_now;
$addresses_cache = $data;
}
return $addresses_cache;
}
实际实例如下
function push(){
//To project A
Gateway::$registerAddress = 'Address1:port';
Gateway::sentToUid('uid', 'msg');
//To project B
Gateway::$registerAddress = 'Address2:port';
Gateway::sentToUid('uid', 'msg');
//To project C
Gateway::$registerAddress = 'Address3:port';
Gateway::isUidOnline('uid';
}
经过断点确实是只会往Address1发送消息;
请问有什么方式能解决这个问题?
自己加个禁用缓存的属性,测试ok后在github上发个pull request吧