nginx的ip_hash算法

概念

根据用户请求的ip,利用算法映射成hash值,分配到特定的tomcat服务器中。主要是为了实现负载均衡,只要用户ip固定,则hash值固定,特定用户只能访问特定服务器,解决了session的问题。

源码分析

ip_hash算法的处理代码位于src\http\modules\ngx_http_upstream_ip_hash_module.c。主要的处理代码如下:

// 最大失败次数、超时时间、最大连接数等相关配置
#define NGX_HTTP_UPSTREAM_CREATE        0x0001
#define NGX_HTTP_UPSTREAM_WEIGHT        0x0002
#define NGX_HTTP_UPSTREAM_MAX_FAILS     0x0004
#define NGX_HTTP_UPSTREAM_FAIL_TIMEOUT  0x0008
#define NGX_HTTP_UPSTREAM_DOWN          0x0010
#define NGX_HTTP_UPSTREAM_BACKUP        0x0020
#define NGX_HTTP_UPSTREAM_MAX_CONNS     0x0100

static ngx_int_t
ngx_http_upstream_get_ip_hash_peer(ngx_peer_connection_t *pc, void *data)
{
    ngx_http_upstream_ip_hash_peer_data_t  *iphp = data;

    time_t                        now;
    ngx_int_t                     w;
    uintptr_t                     m;
    ngx_uint_t                    i, n, p, hash;
    ngx_http_upstream_rr_peer_t  *peer;

    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, pc->log, 0,
                   "get ip hash peer, try: %ui", pc->tries);

    /* TODO: cached */

    ngx_http_upstream_rr_peers_rlock(iphp->rrp.peers);

    if (iphp->tries > 20 || iphp->rrp.peers->single) {
        ngx_http_upstream_rr_peers_unlock(iphp->rrp.peers);
        return iphp->get_rr_peer(pc, &iphp->rrp);
    }

    now = ngx_time();

    pc->cached = 0;
    pc->connection = NULL;

    // 原始哈希值
    hash = iphp->hash;

    for ( ;; ) {

        // 计算ip hash
        for (i = 0; i < (ngx_uint_t) iphp->addrlen; i++) {
            hash = (hash * 113 + iphp->addr[i]) % 6271;
        }

        // 根据hash和权重找到对应服务器
        w = hash % iphp->rrp.peers->total_weight;
        peer = iphp->rrp.peers->peer;
        p = 0;

        while (w >= peer->weight) {
            w -= peer->weight;
            peer = peer->next;
            p++;
        }

        n = p / (8 * sizeof(uintptr_t));
        m = (uintptr_t) 1 << p % (8 * sizeof(uintptr_t));

        if (iphp->rrp.tried[n] & m) {
            goto next;
        }

        ngx_log_debug2(NGX_LOG_DEBUG_HTTP, pc->log, 0,
                       "get ip hash peer, hash: %ui %04XL", p, (uint64_t) m);

        ngx_http_upstream_rr_peer_lock(iphp->rrp.peers, peer);

        // 如果服务器不可用,不做后续处理
        if (peer->down) {
            ngx_http_upstream_rr_peer_unlock(iphp->rrp.peers, peer);
            goto next;
        }

        // 如果超过最大失败次数或者超时,不做后续处理
        if (peer->max_fails
            && peer->fails >= peer->max_fails
            && now - peer->checked <= peer->fail_timeout)
        {
            ngx_http_upstream_rr_peer_unlock(iphp->rrp.peers, peer);
            goto next;
        }

        // 如果超过最大连接数,不做后续处理
        if (peer->max_conns && peer->conns >= peer->max_conns) {
            ngx_http_upstream_rr_peer_unlock(iphp->rrp.peers, peer);
            goto next;
        }

        break;

    next:

        if (++iphp->tries > 20) {
            ngx_http_upstream_rr_peers_unlock(iphp->rrp.peers);
            return iphp->get_rr_peer(pc, &iphp->rrp);
        }
    }

    iphp->rrp.current = peer;

    pc->sockaddr = peer->sockaddr;
    pc->socklen = peer->socklen;
    pc->name = &peer->name;

    // 连接数自增
    peer->conns++;

    if (now - peer->checked > peer->fail_timeout) {
        peer->checked = now;
    }

    ngx_http_upstream_rr_peer_unlock(iphp->rrp.peers, peer);
    ngx_http_upstream_rr_peers_unlock(iphp->rrp.peers);

    iphp->rrp.tried[n] |= m;
    iphp->hash = hash;

    return NGX_OK;
}

算法的核心处理代码如下:

for (i = 0; i < (ngx_uint_t) iphp->addrlen; i++) {
    hash = (hash * 113 + iphp->addr[i]) % 6271;
}

通过查看源码得知,ipv4的情况下iphp->addrlen的值固定为3,源代码如下:

switch (r->connection->sockaddr->sa_family) {

    case AF_INET:   // ipv4
        sin = (struct sockaddr_in *) r->connection->sockaddr;
        iphp->addr = (u_char *) &sin->sin_addr.s_addr;
        iphp->addrlen = 3;  
        break;

#if (NGX_HAVE_INET6)
    case AF_INET6:  // ipv6
        sin6 = (struct sockaddr_in6 *) r->connection->sockaddr;
        iphp->addr = (u_char *) &sin6->sin6_addr.s6_addr;
        iphp->addrlen = 16; 
        break;
#endif

    default:
        iphp->addr = ngx_http_upstream_ip_hash_pseudo_addr;
        iphp->addrlen = 3;
    }

假如我们传递的ip为192.168.41.33,hash值得计算流程可以拆分为:

hash0 = iphp->hash;

# iphp->addr[0]--->192
hash1 = (hash0 * 113 + iphp->addr[0]) % 6271;

# iphp->addr[1]--->168
hash2 = (hash1 * 113 + iphp->addr[1]) % 6271;

# iphp->addr[2]--->41
hash3 = (hash2 * 113 + iphp->addr[2]) % 6271;

经分析得知,ip_hash实际是取ip地址得前三个字段计算得来,那么譬如192.168.41.xxx同一网段的ip访问的是同一个tomacat。

根据hash和权重找到对应的后端,源代码如下:

w = hash % iphp->rrp.peers->total_weight;
peer = iphp->rrp.peers->peer;
p = 0;

while (w >= peer->weight) {
    w -= peer->weight;
    peer = peer->next;
    p++;
}

// ...

需要注意的一点是,当一个正在以ip_hash方式管理的服务器在实际操作环境中被移除时,在nginx.conf中不能直接把对应的配置删除,在后面加down即可,因为删除后需要重新计算hash,处理这一过程会更加消耗资源。nginx.conf配置文件修改如下:

# 以ip_hash的方式实现负载均衡, 添加ip_hash即可
upstream dongserver {
    ip_hash;      
    server 192.168.41.33:8080;
    server 192.168.41.34:8081;
    server 192.168.41.35:8082 down;  # 服务器不可用
}

nginx源码中对此的处理如下:

# upstream块结构体
struct ngx_http_upstream_rr_peer_s {
    //...

    ngx_uint_t                      down;    // 服务器是否可用

    //...
};

# 当判断到down标志被竖起来之后,不做后续处理
if (peer->down) {
    ngx_http_upstream_rr_peer_unlock(iphp->rrp.peers, peer);
    goto next;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`ip_hash`是Nginx的一种负载均衡算法,它基于客户端的IP地址来确定将请求转发给哪个后端服务器。使用`ip_hash`算法,相同IP地址的客户端将始终被分配到同一个后端服务器,这有助于保持会话的一致性。 要配置Nginx使用`ip_hash`算法进行负载均衡,可以按照以下步骤进行: 1. 打开Nginx的配置文件。通常在Linux系统中,配置文件位于`/etc/nginx/nginx.conf`或`/etc/nginx/conf.d/default.conf`。 2. 在`http`块内添加一个`upstream`块,定义要进行负载均衡的服务器列表。示例代码如下: ```nginx http { upstream backend { ip_hash; server backend1.example.com; server backend2.example.com; server backend3.example.com; } ... } ``` 在上面的示例中,我们使用`ip_hash`指令在`upstream`块中启用了IP哈希负载均衡算法,并列出了要进行负载均衡的服务器。 3. 在Nginx的配置文件中,找到你要使用负载均衡的位置(如`location`块),并将其代理到上面定义的`backend`服务器组。示例代码如下: ```nginx http { upstream backend { ip_hash; server backend1.example.com; server backend2.example.com; server backend3.example.com; } server { ... location / { proxy_pass http://backend; } ... } } ``` 在上面的示例中,我们使用`proxy_pass`将请求代理到名为`backend`的服务器组。 4. 保存配置文件并重新加载Nginx配置。在终端中执行以下命令: ```shell sudo nginx -t # 检查配置文件语法是否正确 sudo systemctl reload nginx # 重新加载Nginx配置 ``` 这样配置后,Nginx将使用`ip_hash`算法将请求分发给后端服务器。相同IP地址的客户端将被分配到同一个后端服务器上,从而保持会话的一致性。 请注意,`ip_hash`算法适用于基于客户端IP地址的负载均衡,并且要求Nginx编译时启用了`--with-http_upstream_ip_hash_module`模块。确保你的Nginx版本支持此功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值