src.dualinventive.com/go/websocketserver/internal/redis/event.go

54 lines
972 B
Go

package redis
import (
"hash/adler32"
"sync"
)
// Event holds a single Redis publish message event
type Event struct {
Chan string // Chan holds the publish channel name
Msg string // Msg is the published message data
}
// eventCache caches all Publish events
type eventCache struct {
mu sync.Mutex
evs map[uint32]Event
}
// Add a single publish event to the cache
func (c *eventCache) Add(channel string, msg string) {
// We hash the sum of the channel and message to save RAM and lookup time in the cache
h := adler32.Checksum([]byte(channel + msg))
c.mu.Lock()
if _, ok := c.evs[h]; ok {
c.mu.Unlock()
return
}
c.evs[h] = Event{Chan: channel, Msg: msg}
c.mu.Unlock()
}
// Flush and get all the current publish events
func (c *eventCache) Flush() []Event {
c.mu.Lock()
evs := make([]Event, 0, len(c.evs))
var n = 0
for _, e := range c.evs {
evs = append(evs, e)
n++
}
c.evs = make(map[uint32]Event)
c.mu.Unlock()
return evs
}