终极白嫖怪,这次是用 Cloudflare Workers 实现网站 / API 的负载均衡。

一天用一台,轮着用

废话少说,直接贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})

const servers = [
'1.api.jonbgua.com', '2.api.jonbgua.com'
]

async function handleRequest(request) {
// new URL object to play with,
// based on the one being requested.
var url = new URL(request.url)
// 今天用哪个服务器?
var d = new Date()
const day = d.getDate()
// set hostname to the place we're proxying requests from
url.hostname = servers[day%servers.length]
// pass the modified url back to the request,
let response = await fetch(url, request)
return response;
}

在 servers 数组里面填上若干个备份服务器即可。