一、 问题背景
Atlas对slave进行负载均衡,每一台slave都有一个权重值,权重越大,负载的读请求越多。负载均衡的算法比较巧妙,代码如下:
guint max_weight = rwsplit->max_weight;
guint cur_weight = rwsplit->cur_weight;
guint next_ndx = rwsplit->next_ndx;
// get backend index by slave wrr
gint ndx = -1;
for(i = 0; i < ndx_num; ++i) {
network_backend_t* backend = network_backends_get(backends, next_ndx);
if (backend == NULL) goto next;
network_connection_pool* pool = chassis_event_thread_pool(backend);
if (pool == NULL) goto next;
if (backend->type == BACKEND_TYPE_RO &&
backend->weight >= cur_weight &&
backend->state == BACKEND_STATE_UP)
ndx = next_ndx;
next:
if (next_ndx == ndx_num - 1) {
--cur_weight;
next_ndx = 0;
if (cur_weight == 0) cur_weight = max_weight;
} else {
++next_ndx;
}
if (ndx != -1) break;
}
rwsplit->cur_weight = cur_weight;
rwsplit->next_ndx = next_ndx;