Nginx學習之十三-負載平衡-IP雜湊策略剖析

來源:互聯網
上載者:User

前面介紹過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個位元組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.