feat: add settings cache to reduce database queries in MediaScanner
- Add SettingsCache with TTL-based invalidation (30 seconds) - Cache scan_poll_interval_seconds and auto_scan_enabled settings - Reduce database queries from every poll/check to once per TTL period - Improve error handling with proper fallback values - Simplify boolean parsing with strings.ToLower for consistency This optimization reduces database load when checking scan settings, which occurs frequently during media scanning operations.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SettingsCache struct {
|
||||
data map[string]string
|
||||
mu sync.RWMutex
|
||||
ttl time.Duration
|
||||
lastUpdate time.Time
|
||||
}
|
||||
|
||||
func NewSettingsCache(ttl time.Duration) *SettingsCache {
|
||||
return &SettingsCache{
|
||||
data: make(map[string]string),
|
||||
ttl: ttl,
|
||||
lastUpdate: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *SettingsCache) Get(key string) (string, bool) {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
// Check if cache is expired
|
||||
if time.Since(c.lastUpdate) > c.ttl {
|
||||
return "", false
|
||||
}
|
||||
|
||||
val, ok := c.data[key]
|
||||
return val, ok
|
||||
}
|
||||
|
||||
func (c *SettingsCache) Set(key, value string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.data[key] = value
|
||||
c.lastUpdate = time.Now()
|
||||
}
|
||||
|
||||
func (c *SettingsCache) Invalidate() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
c.data = make(map[string]string)
|
||||
c.lastUpdate = time.Time{}
|
||||
}
|
||||
|
||||
func (c *SettingsCache) InvalidateKey(key string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
delete(c.data, key)
|
||||
}
|
||||
Reference in New Issue
Block a user