Skip to content

Instantly share code, notes, and snippets.

@spdeepak
Created March 13, 2025 17:57
Show Gist options
  • Save spdeepak/70a7010e27fbde3622b7de30f98f8a69 to your computer and use it in GitHub Desktop.
Save spdeepak/70a7010e27fbde3622b7de30f98f8a69 to your computer and use it in GitHub Desktop.
Polling in go for caching
package cache
import (
"sync"
"time"
)
type PollCache[K comparable, V any] struct {
data sync.Map
pollFunc func() map[K]V
interval time.Duration
}
// NewPollCache initializes a new cache with a polling mechanism
func NewPollCache[K comparable, V any](pollFunc func() map[K]V, interval time.Duration) *PollCache[K, V] {
pc := &PollCache[K, V]{
pollFunc: pollFunc,
interval: interval,
}
go pc.startPolling()
return pc
}
// startPolling continuously updates the cache in a given interval
func (pc *PollCache[K, V]) startPolling() {
for {
newData := pc.pollFunc()
pc.data = sync.Map{} // Reset the map before storing new values
for k, v := range newData {
pc.data.Store(k, v)
}
time.Sleep(pc.interval)
}
}
// Get retrieves a value from the cache
func (pc *PollCache[K, V]) Get(key K) (V, bool) {
val, exists := pc.data.Load(key)
if exists {
return val.(V), true
}
var zeroValue V
return zeroValue, false
}
// GetMultiple retrieves multiple values from the cache based on keys
func (pc *PollCache[K, V]) GetMultiple(keys ...K) []V {
var results []V
for _, key := range keys {
if val, exists := pc.Get(key); exists {
results = append(results, val)
}
}
return results
}
// GetAll retrieves all values from the cache
func (pc *PollCache[K, V]) GetAll() []V {
var results []V
pc.data.Range(func(_, value any) bool {
results = append(results, value.(V))
return true
})
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment