全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 8 分钟 ✍️ juanwangdev

会话保持

会话保持确保同一客户端请求始终路由到同一后端服务器,适用于有状态应用场景。

IP Hash

内置方案

nginx
upstream backend {
    ip_hash;

    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080 down;
    server 10.0.0.4:8080;
}

算法原理

C
// IPv4 哈希
hash = (client_ip[0] * 119 + client_ip[1]) * 119 + client_ip[2];
hash = hash * 119 + client_ip[3];

// 取模路由
peer_index = hash % peer_count;

IP Hash 基于客户端 IP 前三段计算,IPv6 使用前四段。down 标记的服务器不参与计算。

Cookie 注入

Nginx Plus 方案

nginx
upstream backend {
    zone backend 64k;

    server 10.0.0.1:8080;
    server 10.0.0.2:8080;

    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

OpenResty 方案

lua
-- sticky.lua
local balancer = require("ngx.balancer")

local function get_sticky_peer(peers)
    local cookie = ngx.var.cookie_SRV_ID

    if cookie then
        for i, peer in ipairs(peers) do
            if peer.id == cookie then
                return peer
            end
        end
    end

    -- 首次访问,选择并设置 Cookie
    local peer = peers[math.random(#peers)]
    ngx.header["Set-Cookie"] = "SRV_ID=" .. peer.id .. "; Path=/; Max-Age=3600"
    return peer
end

Cookie 参数

参数说明
expiresCookie 有效期
domainCookie 域名
pathCookie 路径
httponly禁止 JS 访问
secure仅 HTTPS 传输

一致性哈希

一致性哈希环

nginx
upstream backend {
    hash $request_uri consistent;

    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
    server 10.0.0.3:8080;
}

哈希键选择

哈希键适用场景
$request_uriAPI 缓存、静态资源
$cookie_session用户会话
$arg_user_id用户维度
$binary_remote_addrIP 维度

一致性哈希确保节点增减时仅少量请求重路由,适用于缓存场景。

会话同步方案

共享存储

nginx
# Redis 存储会话
upstream backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;

    sticky route $cookie_session;
}

# OpenResty 读取 Redis
location /api {
    access_by_lua_block {
        local redis = require("resty.redis")
        local red = redis:new()
        red:connect("127.0.0.1", 6379)

        local session = ngx.var.cookie_session
        local server = red:get("session:" .. session)

        if server then
            -- 路由到指定服务器
            ngx.balancer.set_current_peer(server)
        end
    }
}

JWT 方案

lua
-- JWT 包含服务器信息
local jwt = {
    header = { alg = "HS256", typ = "JWT" },
    payload = {
        sub = user_id,
        srv = "10.0.0.1",  -- 服务器标识
        exp = os.time() + 3600
    }
}

要点总结

  • IP Hash 基于客户端 IP 计算,简单但负载均衡不均
  • Cookie 注入通过 Set-Cookie 实现精确会话绑定
  • 一致性哈希适用于缓存场景,节点变更影响范围小
  • 共享存储(Redis)实现分布式会话,支持故障转移
  • JWT 方案将会话信息编码到令牌,无需服务器端存储

📝 发现内容有误?点击此处直接编辑

← 上一篇 Nginx 缓冲区大小配置(client_body_buffer_size, proxy_buffer_size)
下一篇 → 健康检查机制
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库