51 lines
1.3 KiB
Go
51 lines
1.3 KiB
Go
// bulma/atomic_mutex_hybrid.go
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
// RequestCounter 请求计数器(混合方案:原子操作+Mutex)
|
|
type RequestCounter struct {
|
|
total atomic.Uint64 // 高频累加,用原子操作
|
|
mu sync.Mutex // 互斥锁,保护复杂数据结构(map)
|
|
details map[string]uint64 // 复杂结构,用 Mutex 保护
|
|
}
|
|
|
|
// Inc 累加请求数:包含高频简单操作与复杂结构更新
|
|
func (rc *RequestCounter) Inc(endpoint string) {
|
|
rc.total.Add(1) // 无锁累加总数
|
|
|
|
// 复杂数据结构更新(map写入),通过加锁保护,避免数据竞争
|
|
rc.mu.Lock()
|
|
rc.details[endpoint]++
|
|
rc.mu.Unlock()
|
|
}
|
|
|
|
// Stats 获取统计结果:通过深拷贝,避免外部修改内部数据
|
|
func (rc *RequestCounter) Stats() (uint64, map[string]uint64) {
|
|
rc.mu.Lock()
|
|
defer rc.mu.Unlock()
|
|
// 深拷贝避免外部修改
|
|
copyDetails := make(map[string]uint64, len(rc.details))
|
|
for k, v := range rc.details {
|
|
copyDetails[k] = v
|
|
}
|
|
return rc.total.Load(), copyDetails
|
|
}
|
|
|
|
func main() {
|
|
rc := &RequestCounter{details: make(map[string]uint64)}
|
|
// 模拟3次接口请求
|
|
rc.Inc("/api/users")
|
|
rc.Inc("/api/posts")
|
|
rc.Inc("/api/users")
|
|
|
|
// 查看统计结果
|
|
total, details := rc.Stats()
|
|
fmt.Printf("✅ 总请求数: %d\n", total)
|
|
fmt.Printf("✅ 详情: %+v\n", details)
|
|
}
|