根据接口名称以及配置好的权重信息获取一个host :param interface: :return:
(self, interface)
| 249 | self.zk.create_async(consumer_path + '/' + quote(consumer, safe=''), ephemeral=True) |
| 250 | |
| 251 | def _routing_with_wight(self, interface): |
| 252 | """ |
| 253 | 根据接口名称以及配置好的权重信息获取一个host |
| 254 | :param interface: |
| 255 | :return: |
| 256 | """ |
| 257 | hosts = self.hosts[interface] |
| 258 | if not hosts: |
| 259 | raise RegisterException('no providers for interface {}'.format(interface)) |
| 260 | # 此接口没有权重设置,使用朴素的路由算法 |
| 261 | if interface not in self.weights or not self.weights[interface]: |
| 262 | return random.choice(hosts) |
| 263 | |
| 264 | weights = self.weights[interface] |
| 265 | hosts_weight = [] |
| 266 | for host in hosts: |
| 267 | hosts_weight.append(int(weights.get(host, 100))) |
| 268 | |
| 269 | hit = random.randint(0, sum(hosts_weight) - 1) |
| 270 | for i in xrange(len(hosts)): |
| 271 | if hit <= sum(hosts_weight[:i + 1]): |
| 272 | return hosts[i] |
| 273 | |
| 274 | raise RegisterException('Error for finding [{}] host with weight.'.format(interface)) |
| 275 | |
| 276 | def close(self): |
| 277 | self.zk.stop() |
no test coverage detected