背景
没事干,研究研究优选及负载均衡。
一开始我在用cloudflare的worker免费实现负载均衡,
搭配上cloudflare的优选。
worker源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
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);
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即可。
尾声
本次开发日志到此为止,
希望能帮到更多的人。