前面介紹過nginx負載平衡的加權輪詢策略(http://blog.csdn.net/xiajun07061225/article/details/9318871),它是Nginx負載平衡的基礎策略,所以一些初始化工作,比如配置值轉儲,其他策略可以直接複用他。在後面的初始化的代碼中將可以看到。
註:本文中原始碼版本為Nginx-1.4.0。
IP雜湊初始化
IP雜湊的初始化函數ngx_http_upstream_init_ip_hash(ngx_http_upstream_ip_hash_module.c): [cpp] view plain copy print ? static ngx_int_t ngx_http_upstream_init_ip_hash(ngx_conf_t *cf, ngx_http_upstream_srv_conf_t *us) { //調用了加權輪詢 if (ngx_http_upstream_init_round_robin(cf, us) != NGX_OK) { return NGX_ERROR; } //修改了針對單個請求進行初始化的回呼函數 us->peer.init = ngx_http_upstream_init_ip_hash_peer; return NGX_OK; }
選擇後端伺服器
當用戶端請求過來之後,將會執行初始化函數ngx_http_upstream_init_ip_hash_peer。其中調用了輪詢演算法中的初始化函數。 原始碼: [cpp] view plain copy print ? static ngx_int_t ngx_http_upstream_init_ip_hash_peer(ngx_http_request_t *r, ngx_http_upstream_srv_conf_t *us) { struct sockaddr_in *sin; //針對IPv6的支援 #if (NGX_HAVE_INET6) struct sockaddr_in6 *sin6; #endif ngx_http_upstream_ip_hash_peer_data_t *iphp; iphp = ngx_palloc(r->pool, sizeof(ngx_http_upstream_ip_hash_peer_data_t)); if (iphp == NULL) { return NGX_ERROR; } r->upstream->peer.data = &iphp->rrp; //調用了RR演算法中的初始化函數 if (ngx_http_upstream_init_round_robin_peer(r, us) != NGX_OK) { return NGX_ERROR; } //回呼函數設定,具體做選擇的回呼函數 r->upstream->peer.get = ngx_http_upstream_get_ip_hash_peer; switch (r->connection->sockaddr->sa_family) { //儲存用戶端地址 case AF_INET: sin = (struct sockaddr_in *) r->connection->sockaddr; iphp->addr = (u_char *) &sin->sin_addr.s_addr; //轉儲IPv4隻用到了前3個位元組,因為在後面的hash計算過程中只用到了3個位元組