背景

没事干,研究研究优选及负载均衡。

一开始我在用cloudflare的worker免费实现负载均衡,
搭配上cloudflare的优选。
worker源码:

/**
 * 合规说明:
 * 本脚本仅用于个人/自有业务的反向代理与路由分发。
 * 仅代理至用户合法拥有的域名/服务,不提供公共代理、VPN、翻墙服务。
 * 不使用 Cloudflare 代理加速,仅做请求转发,符合 Cloudflare 条款。
 */

// ===================== 配置区 =====================
const BACKENDS = {
  CN: [
    { u: "https://cn.site.com", w: 70 },
    { u: "https://cn2.site.com", w: 30 },
  ],
  US: [
    { u: "https://us.site.com", w: 80 },
    { u: "https://us2.site.com", w: 20 },
  ],
  default: [
    { u: "https://global.site.com", w: 100 },
  ],
};

const HEALTH_TIMEOUT = 3000;
const HEALTH_CACHE_TTL = 30;
// ===================================================

let healthCache = {};

export default {
  async fetch(req) {
    const url = new URL(req.url);
    const country = req.cf?.country || "default";
    const nodes = BACKENDS[country] || BACKENDS.default;
    const now = Date.now();

    // 筛选健康节点
    const healthy = [];
    let totalW = 0;

    for (const node of nodes) {
      let ok = false;

      // 缓存判断
      if (healthCache[node.u] && now < healthCache[node.u].e) {
        ok = healthCache[node.u].h;
      } else {
        try {
          const res = await fetch(node.u, { timeout: HEALTH_TIMEOUT });
          ok = res.ok;
        } catch {
          ok = false;
        }
        healthCache[node.u] = { h: ok, e: now + HEALTH_CACHE_TTL * 1000 };
      }

      if (ok) {
        healthy.push(node);
        totalW += node.w;
      }
    }

    if (healthy.length === 0) {
      return new Response("Service Unavailable", { status: 503 });
    }

    // 权重选择
    let rand = Math.random() * totalW;
    const target = healthy.find(n => (rand -= n.w) <= 0).u;
    const dest = new URL(url.pathname + url.search, target);

    // 转发请求(纯反代,不开CF代理)
    return fetch(dest, {
      method: req.method,
      headers: (h => (h.delete("host"), h))(new Headers(req.headers)),
      body: req.body,
    });
  },
};

部署教程:
cloudflare worker部署完后,绑定路由(https://域名/*
然后到dns控制台,
上面域名记录:
CNAME 域名 优选(如mfa.gov.ua等)
就行了。

看完Cloudflare用户协议后打消了这个念头。

然后就去捣鼓Vercel的优选,
vercel本来在测试中有橙、黄、绿,
不稳定。

上了固定ip后,见图:

(由AntPing检测)


(由itDog检测)

正文

很简单,
vercel项目绑定域名后,
将默认的CNAME记录xxxxxxxxxxxxxxxx.vercel-dns-xxx.com
改为CNAME记录vercel.dns.imjcj.eu.org即可。
改为CNAME记录cname-china.vercel-dns.com即可。