全部学科
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 方案将会话信息编码到令牌,无需服务器端存储
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 健康检查机制
下一篇 → 灰度发布策略
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码