perf: 优化后端性能与直播延迟,包含数据库WAL模式、流媒体写缓冲、转码 Preset 优化、聊天锁和指标采集优化,以及前端自动追帧功能

This commit is contained in:
2026-06-15 15:08:07 +08:00
parent 261b1ab169
commit e0a6923984
5 changed files with 150 additions and 24 deletions

View File

@@ -2,6 +2,7 @@ package monitor
import (
"runtime"
"sync"
"sync/atomic"
"time"
)
@@ -23,21 +24,32 @@ type Snapshot struct {
ErrorsTotal uint64 `json:"errors_total"`
}
func IncrementRequestCount() {
atomic.AddUint64(&totalRequests, 1)
var (
cachedSnapshot Snapshot
snapshotMutex sync.RWMutex
)
func init() {
// Initialize the snapshot once on startup
updateSnapshot()
// Update the snapshot in the background every 2 seconds to avoid STW runtime.ReadMemStats in request threads
go func() {
ticker := time.NewTicker(2 * time.Second)
for range ticker.C {
updateSnapshot()
}
}()
}
func IncrementErrorCount() {
atomic.AddUint64(&totalErrors, 1)
}
func GetSnapshot() Snapshot {
func updateSnapshot() {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
diskTotal, diskFree := getDiskSpaceGB()
return Snapshot{
snapshotMutex.Lock()
cachedSnapshot = Snapshot{
UptimeSeconds: int64(time.Since(startedAt).Seconds()),
Goroutines: runtime.NumGoroutine(),
MemoryAllocMB: bytesToMB(mem.Alloc),
@@ -48,6 +60,28 @@ func GetSnapshot() Snapshot {
RequestsTotal: atomic.LoadUint64(&totalRequests),
ErrorsTotal: atomic.LoadUint64(&totalErrors),
}
snapshotMutex.Unlock()
}
func IncrementRequestCount() {
atomic.AddUint64(&totalRequests, 1)
}
func IncrementErrorCount() {
atomic.AddUint64(&totalErrors, 1)
}
func GetSnapshot() Snapshot {
snapshotMutex.RLock()
defer snapshotMutex.RUnlock()
// Return the cached snapshot, overlaying volatile/cheap fields in real-time
s := cachedSnapshot
s.UptimeSeconds = int64(time.Since(startedAt).Seconds())
s.Goroutines = runtime.NumGoroutine()
s.RequestsTotal = atomic.LoadUint64(&totalRequests)
s.ErrorsTotal = atomic.LoadUint64(&totalErrors)
return s
}
func bytesToMB(v uint64) float64 {