Cloudflare Worker实现一个投票应用

起因需求

本意是想在网页里加上一个点击助力的小功能,由于数据只需要一个票数 且无闲置服务器,便研究了一下 Worker KV 如何实现此需求。

后端

1.注册一个Cloudflare账户

2.创建一个 KV 空间,名字随意

3.在 KV 空间内新增一个密钥,取名 vote

4.创建一个 Worker

5.在 worker 的设置 → 变量 →KV 命名空间绑定

添加绑定,命名空间为刚才创建的应用,变量自行命名

以下是初步代码,请将 voteApp 替换为刚取得变量名

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).catch((err) => {
return new Response(err.stack, { status: 500 });
})
);
});
async function handleRequest(event) {
let t = await voteApp.get("vote");
t = parseInt(t) || 0;
const requestBody = await event.request.text();
const contains = requestBody.includes("TP");
if (contains) {
t += 1;
await voteApp.put("vote", t);
return new Response(t);
} else {
return new Response("投票失败");
}
}

该函数会检测请求内容里包不包含 TP,包含则票数加一

改进

处理并发问题

1
2
3
4
5
6
if (contains) {
event.waitUntil(voteApp.put("vote", (t + 1).toString()));
return new Response((t + 1).toString());
} else {
return new Response("投票失败");
}

增加缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
async function handleRequest(event) {
const cache = caches.default;
const cacheKey = "vote_count";
let response = await cache.match(cacheKey);

if (!response) {
const data = await voteApp.get("vote");
let t = parseInt(await data.text()) || 0;

const requestBody = await event.request.text();
const contains = requestBody.includes("TP");

if (contains) {
event.waitUntil(voteApp.put("vote", (t + 1).toString()));
return new Response((t + 1).toString());
} else {
return new Response("投票失败");
}
await cache.put(cacheKey, new Response(t.toString()));
response = new Response(t.toString());
}
return response;
}

前端

仅供参考

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<p>当前票数: <span id="voteCount">0</span></p>
<button onclick="incrementVote()">增加票数</button>
<script>
document.getElementById("voteCount").textContent = "0";
fetch('/vote', { method: 'GET' })
.then(response => response.text())
.then(voteCount => {
document.getElementById("voteCount").textContent = voteCount;
})
.catch(error => {
console.error('显示票数失败', error);
});
function incrementVote() {
fetch('/vote', { method: 'POST' })
.then(response => response.text())
.then(voteCount => {
document.getElementById("voteCount").textContent = voteCount;
})
.catch(error => {
console.error('增加票数失败:', error);
});
}
</script>

Cloudflare Worker实现一个投票应用

http://wxory.com/archives/47477.html

作者

Wxory

发布于

2023-06-09

更新于

2024-05-18

许可协议

CC BY 4.0

评论