当实验需要按城市维度切流,如何对接高德 API 实现 GeoIP?

解读

面试官把“切流”与“GeoIP”两个关键词同时抛给候选人,本质是在考察:

  1. 能否在 Gunicorn 进程模型 下,把“IP→城市”这一外部 IO 做成 毫秒级、高并发、零阻塞 的组件;
  2. 能否在 中国合规场景 里,用 高德 Web 服务 API 完成 地理编码 并 本地缓存,避免 QPS 封顶 与 牌照风险;
  3. 能否把结果无缝注入 实验分流逻辑(AB 实验平台或网关层),并保证 平滑重启 与 热升级 时 缓存不丢、配置不裂。

一句话:不是“调个 HTTP 接口”那么简单,而是要让 Gunicorn worker 在 pre-fork 之后依旧 稳、准、快 地告诉你“这个 IP 是不是北京”。

知识点

  1. Gunicorn pre-fork 模型:master 先 fork,worker 后处理请求;任何阻塞 IO 都会拖住 sync worker,必须用 gevent 或 自定义 async worker。
  2. 高德 GeoIP 接口:https://restapi.amap.com/v5/ip?ip={}&key={}&type=4,返回 adcode 与 城市名;企业认证 后 QPS=200,个人开发者 仅 50,需 缓存。
  3. 中国 IP 分配:三大运营商每日漂移,IPv4 归属地 粒度到 地级市 已足够做 城市实验,IPv6 需额外 /48 映射表。
  4. 切流标识:通常放在 HTTP Header(X-City-Code)或 Cookie(city_ab),供 下游实验框架 消费。
  5. 缓存策略:
    • 进程内 LRU(lru-dict)应对 毫秒级热 Key;
    • 共享内存(multiprocessing.Manager)在 reload 时存活;
    • Redis 做 跨机 与 容灾;
    • 本地 SQLite+WAL 模式做 冷启动兜底。
  6. 合规:高德 要求 用户 IP 不得落盘(隐私合规),只能 缓存 adcode,且 24 h 内 自动失效。
  7. 可观测:用 Gunicorn logger 输出 gunicorn.access 格式,字段里加 city_code 与 cache_hit,对接 Prometheus 的 Counter 与 Histogram。

答案

下面给出一份可直接落地到 生产 Gunicorn 的 最小可运行方案,采用 gevent worker + 进程内 LRU + 异步高德调用,并演示如何在 平滑重启 时 保留缓存。

  1. 安装依赖

    pip install gunicorn[gevent] aiohttp lru-dict python-dotenv
    
  2. 高德客户端(非阻塞版)

    # geoip.py
    import os, aiohttp, asyncio
    from lru import LRU
    
    LRU_SIZE = 50_000          # 约 200 MB 内存
    CACHE_TTL = 3600 * 6       # 6 小时,合规小于 24 h
    GAODE_KEY = os.getenv("GAODE_KEY")
    
    class GeoIP:
        _session = None
        _cache = LRU(LRU_SIZE)
    
        @classmethod
        def get_session(cls):
            if cls._session is None:
                connector = aiohttp.TCPConnector(limit=100, limit_per_host=30)
                cls._session = aiohttp.ClientSession(connector=connector)
            return cls._session
    
        @classmethod
        async def ip_to_city(cls, ip: str) -> str:
            if ip in cls._cache:
                return cls._cache[ip]
            url = f"https://restapi.amap.com/v5/ip"
            params = {"ip": ip, "key": GAODE_KEY, "type": "4"}
            async with cls.get_session().get(url, params=params, timeout=1.5) as resp:
                if resp.status != 200:
                    return "000000"          # 未知城市
                js = await resp.json()
                city_code = js.get("city", "000000")
                cls._cache[ip] = city_code
                return city_code
    
  3. WSGI 应用(Flask 示例)

    # app.py
    from flask import Flask, request, g
    from geoip import GeoIP
    import asyncio
    
    app = Flask(__name__)
    
    def async_run(coro):
        # gevent 里复用已有 loop
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(coro)
    
    @app.before_request
    def inject_city():
        ip = request.headers.get("X-Real-IP") or request.remote_addr
        g.city = async_run(GeoIP.ip_to_city(ip))
        request.headers = dict(request.headers, X-City-Code=g.city)
    
    @app.route("/")
    def index():
        return {"city": g.city}
    
  4. Gunicorn 启动脚本(带 preload 与 graceful reload)

    # run.sh
    export GAODE_KEY=your_key
    exec gunicorn app:app \
         -k gevent \
         -w 8 \
         --worker-connections 1000 \
         --preload \
         --max-requests 10000 \
         --max-requests-jitter 500 \
         --graceful-timeout 30 \
         --bind 0.0.0.0:8000 \
         --access-logformat '%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" city=%({X-City-Code}i)s'
    

    关键点:

    • --preload 让 GeoIP._cache 在 master 里初始化,fork 后 子进程 继承同一份 只读页,内存零拷贝;
    • gevent 保证 8000 并发 下 不会阻塞;
    • access log 直接带上 city 字段,Prometheus exporter 可实时聚合 城市级成功率。
  5. 平滑重启缓存不丢
    由于 --preload 把 LRU 放在 master,HUP 信号仅 重新加载业务代码,旧 worker 优雅退出 时 缓存仍在 master,新 worker 瞬间复用,命中率 不会抖动。

拓展思考

  1. 双通道容灾:当 高德 超 QPS 或 返回 402 时,可 降级 到 本地 IP 库(如 ip2region),adcode 映射表 只需 400 KB,命中率 95% 以上,RT 从 80 ms 降到 0.3 ms。
  2. IPv6 场景:IPv6 /32 归属地 常跨省份,需把 高德 返回的 adcode 与 BGP 宣告段 做 二次校准,缓存 key 改为 /48 前缀。
  3. 实验平台联动:把 X-City-Code 注入 OpenResty 层,lua-resty-experiment 根据 城市+用户段 做 灰度哈希,Gunicorn 只需 透传 header,**实现城市级 金丝雀发布。
  4. 缓存一致性:如果 多机房 部署,Redis 用 RediSearch 模块存 adcode,TTL 随机偏移 5%,防止缓存雪崩;Gunicorn worker 启动时 异步预热 TOP 2000 热门 IP,冷启动命中率 直接 > 90%。
  5. 合规升级:高德 已上线 “差分隐私” 版本,返回 6 位 adcode 后 2 位抹零,实验分流 需把 城市粒度 升到 省级;Gunicorn 侧只需 配置开关 city_truncated=true,无需改代码。

掌握以上思路,候选人即可在 面试 里把“调个接口”讲成“高并发、高可用、合规、可观测”的 工业级方案,稳稳拿到 Gunicorn 方向 的 加分项。