Excellent software and practical tutorials
Using Cloudflare Workers for website offloading
How to use Cloudflare Workers for load balancing, Cloudflare Workers website traffic diversion configuration, Cloudflare Workers load balancing code examples, Implementing weight-based traffic distribution, Cloudflare Workers performance monitoring and optimization!
Cloudflare Workers 是一个强大的服务器端 JavaScript 运行环境,允许你在 Cloudflare 的边缘网络上运行自定义代码。通过 Cloudflare Workers,你可以灵活地管理网站流量,实现分流和Load BalancingThis article will show you how to use Cloudflare Workers toWebsite diversionload, improve website stability and performance.
1. Creating a Cloudflare Worker
- Register and log in: First, you need to register and log in to your account on Cloudflare’s official website.
- Creating a Worker: In the Cloudflare dashboard, select the “Workers” option and click the “Create a Service” button. Give your Worker a name and create the service.
- Writing Code: You can write your Worker code in Cloudflare's online editor, or develop using a local development environment and deploy to Cloudflare.
2. Implementing basic load balancing
Writing load balancing code: In the Worker code, you can use JavaScript to implement basic load balancing. The following is a simple example code that will divert traffic to multiple servers:
const BACKENDS = [ 'https://backend1.example.com', 'https://backend2.example.com', 'https://backend3.example.com' ]; addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { const url = new URL(request.url); const backend = BACKENDS[Math.floor(Math.random() * BACKENDS.length)]; url.hostname = new URL(backend).hostname; return fetch(url.toString(), request); }
This code snippet will randomly distribute requests to
BACKENDS
Different backend servers in an array.Configuring routing rules: In the Cloudflare Workers configuration page, set up routing rules to specify which requests should use the Worker you created. You can configure these rules based on path, hostname, or other request attributes.
3. Implementing weight-based load balancing
Setting weights: If you want to distribute traffic according to specific weights, you can modify the above code and use weights to determine request distribution. The following is an example:
const BACKENDS = [ { url: 'https://backend1.example.com', weight: 1 }, { url: 'https://backend2.example.com', weight: 3 }, { url: 'https://backend3.example.com', weight: 1 } ]; addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { const url = new URL(request.url); const backend = getWeightedBackend(); url.hostname = new URL(backend.url).hostname; return fetch(url.toString(), request); } function getWeightedBackend() { let totalWeight = BACKENDS.reduce((sum, backend) => sum + backend.weight, 0); let random = Math.random() * totalWeight; for (let backend of BACKENDS) { if (random < backend.weight) { return backend; } random -= backend.weight; } }
This code selects the backend server according to the specified weight, thereby achieving weighted distribution of traffic.
4. Monitoring and Optimization
- Monitoring Worker Performance: Use Cloudflare's analytics tools to monitor Worker performance, including request response time, error rate, etc. This data can help you adjust your load balancing strategy to optimize performance.
- Optimizing the code: Optimize your Worker code based on the monitoring results to ensure efficient and stable load balancing.
5. Testing and deployment
- Testing Workers: Before deploying, test the functionality of your Worker using Cloudflare's testing tools to ensure it works as expected.
- Deploy to production environment: After the test passes, deploy the Worker to the production environment and make adjustments based on traffic conditions.
Cloudflare Workers hands-on tutorial
After hosting the domain name on the Cloudflare platform, Cloudflare Workers is used to load balance the website domain name.
Here are some strategies for diverting resources:
- DNS round robin
- Open source platforms Nginx, Apache, etc.
- Load loader services provided by major cloud vendors, etc.
- CND
At first, I wanted to try the smart DNS service of Cloudflare platform, but it needs to be paid ($5/mo). So I wanted to try it through Cloudflare Workers.
Sign up for a Cloudflare account
- Go Cloudflare Register an account and host the domain name to CF
- Adding a CNAME record will
a.aaa.com
Resolve to A server IP - Adding an A record will
b.aaa.com
Resolve to server B IP - SSL/TLS in full strict mode
- (must) Enable Proxy in DNS record (Xiaoju Cloud)
Creating Workers
- Go to Workers and Pages
- choose
Create an application
- Paste the following code
addEventListener('fetch', event => {event.respondWith(handleRequest(event.request)) }) // Polling target service const TARGETS = [ 'a.aaa.com', 'b.aaa.com' ] async function handleRequest(request) {const url = new URL(request.url) url.hostname = getRandomServer() return await fetch(url, request) } // Switch different targets every hour function getServerEveryHour() {const d = new Date() const h = d.getHours() return TARGETS[h%TARGETS.length] } // Random target every time (pay attention to whether there is cross-domain between targets) function getRandomServer() {return TARGETS[Math.floor(Math.random() * TARGETS.length)] }
- Save and deploy
Using Workers
- View the newly created Worker and select the trigger on the details page
- In routingInterface clickAdding Routes
- Route: optional
aaa.com
, wildcards can be used.Specific visible - Select the area you just created.
aaa.com
- Route: optional
verify
Click on the top right corner of the Workers configuration page you just created to edit, debug, and preview the JavaScript code.
Modify this code to verify whether the diversion is effective:
// Polling target service const TARGETS = [ 'a.aaa.com', 'b.aaa.com' ]
Refresh the page and sometimes you will find that it loads to a.aaa.com, which means the configuration is effective!