Golang中如何将返回值存储到本地缓存
Golang中如何将返回值存储到本地缓存 我正在开发一个程序,其目的是让客户端将本地缓存中的鼠标点击次数作为HTTP响应返回。当在网页上点击鼠标右键时,该值应增加一;当点击鼠标左键时,该值也应增加一。我在返回这些值时遇到了困难。
这是我的完整HTML代码:https://pastebin.com/JKJtEXjh
这是我的CACHE函数:https://pastebin.com/d2fZk3Pe
这是我的数据库和Web服务器命令:https://pastebin.com/mWGgNLd9
更多关于Golang中如何将返回值存储到本地缓存的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于Golang中如何将返回值存储到本地缓存的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中实现本地缓存存储返回值,可以使用sync.Map或第三方缓存库。以下是基于你需求的解决方案:
package main
import (
"fmt"
"net/http"
"sync"
"time"
)
// 使用sync.Map作为线程安全的本地缓存
var cache sync.Map
// 点击计数器结构
type ClickCounter struct {
LeftClick int
RightClick int
LastUpdate time.Time
}
// 获取点击次数
func getClicks(w http.ResponseWriter, r *http.Request) {
// 从缓存获取数据
if val, ok := cache.Load("clicks"); ok {
counter := val.(ClickCounter)
response := fmt.Sprintf("左键点击: %d, 右键点击: %d",
counter.LeftClick, counter.RightClick)
w.Write([]byte(response))
return
}
// 缓存不存在时初始化
counter := ClickCounter{LastUpdate: time.Now()}
cache.Store("clicks", counter)
w.Write([]byte("点击计数器已初始化"))
}
// 增加左键点击
func incrementLeftClick(w http.ResponseWriter, r *http.Request) {
updateClickCounter(func(counter *ClickCounter) {
counter.LeftClick++
counter.LastUpdate = time.Now()
})
w.Write([]byte("左键点击已增加"))
}
// 增加右键点击
func incrementRightClick(w http.ResponseWriter, r *http.Request) {
updateClickCounter(func(counter *ClickCounter) {
counter.RightClick++
counter.LastUpdate = time.Now()
})
w.Write([]byte("右键点击已增加"))
}
// 更新点击计数器的通用函数
func updateClickCounter(updateFunc func(*ClickCounter)) {
// 使用LoadOrStore确保线程安全
val, _ := cache.LoadOrStore("clicks", ClickCounter{LastUpdate: time.Now()})
counter := val.(ClickCounter)
updateFunc(&counter)
cache.Store("clicks", counter)
}
// 带TTL的缓存版本(可选)
type CacheItem struct {
Value interface{}
Expiration int64
}
var cacheWithTTL sync.Map
func setWithTTL(key string, value interface{}, ttl time.Duration) {
cacheWithTTL.Store(key, CacheItem{
Value: value,
Expiration: time.Now().Add(ttl).UnixNano(),
})
}
func getWithTTL(key string) (interface{}, bool) {
if val, ok := cacheWithTTL.Load(key); ok {
item := val.(CacheItem)
if time.Now().UnixNano() > item.Expiration {
cacheWithTTL.Delete(key)
return nil, false
}
return item.Value, true
}
return nil, false
}
func main() {
http.HandleFunc("/clicks", getClicks)
http.HandleFunc("/click/left", incrementLeftClick)
http.HandleFunc("/click/right", incrementRightClick)
fmt.Println("服务器启动在 :8080")
http.ListenAndServe(":8080", nil)
}
对应的HTML修改:
<!DOCTYPE html>
<html>
<body>
<h2>点击计数器</h2>
<button onclick="incrementLeftClick()">左键点击</button>
<button onclick="incrementRightClick()">右键点击</button>
<button onclick="getClickCount()">获取点击次数</button>
<div id="result"></div>
<script>
async function incrementLeftClick() {
await fetch('/click/left', { method: 'POST' });
}
async function incrementRightClick() {
await fetch('/click/right', { method: 'POST' });
}
async function getClickCount() {
const response = await fetch('/clicks');
const data = await response.text();
document.getElementById('result').innerText = data;
}
// 监听页面点击事件
document.addEventListener('click', incrementLeftClick);
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
incrementRightClick();
});
</script>
</body>
</html>
这个实现提供了:
- 线程安全的本地缓存使用
sync.Map - 分别处理左键和右键点击的HTTP端点
- 可选的TTL缓存机制
- 完整的客户端-服务器交互
运行命令:
go run main.go

