策略一:
服务器进行分布式部署;
接口通过乐观锁机制实时处理扣费/加钱等操作(如:UPDATE user SET amount = amount - ${amount} WHERE id = ${user_id} AND amount - ${amount} > 0);
某些非关键操作,如礼物统计、榜单更新等,全部通过消息队列异步完成;
对于连续高频的打赏行为,采用批量写入策略(客户端进行延时控制),减轻实时压力
策略二:
通过单点服务器进行延时控制
package main import ( "fmt" "log" "math/rand" "net/http" "sync" "time" ) type UserCount struct { timer *time.Timer count int } var mapUserCount = map[int]UserCount{} var mu sync.Mutex /// 思路: 通过 time.AfterFunc 处理延时任务 func delay(w http.ResponseWriter, r *http.Request) { mu.Lock() defer mu.Unlock() rand.Seed(time.Now().Unix()) userId := rand.Intn(3) timeout := time.Second userCount, ok := mapUserCount[userId] if ok { fmt.Fprintln(w, "ok") userCount.count++ userCount.timer.Reset(timeout) // 更新计时器 } else { fmt.Fprintln(w, "not ok") userCount.count = 1 userCount.timer = time.AfterFunc(timeout, func() { // 新建计时器 totalCount := mapUserCount[userId].count fmt.Println("userId:", userId, ", total count:", totalCount, ", key deleted.") // todo: 业务逻辑部分 // ... delete(mapUserCount, userId) // 删除 key }) } mapUserCount[userId] = userCount // todo: 发送 IM 推送消息 fmt.Fprintln(w, "userId:", userId) fmt.Fprintln(w, "userCount:", userCount) } func main() { http.HandleFunc("/", delay) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
文档更新时间: 2024-04-20 10:57 作者:lee