Implement KeepUpdated. Switch to Logrus logger. Relocate score-related functions.
This commit is contained in:
39
internal/cache/cache.go
vendored
39
internal/cache/cache.go
vendored
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
@@ -12,12 +13,14 @@ import (
|
||||
var ctx = context.Background()
|
||||
|
||||
type PlayerCache struct {
|
||||
cache *redis.Client
|
||||
lifetime time.Duration
|
||||
cache *redis.Client
|
||||
lifetime time.Duration
|
||||
expireSub *redis.PubSub
|
||||
expireCallback func(key string)
|
||||
}
|
||||
|
||||
func NewPlayerCache(address string, lifetime time.Duration) *PlayerCache {
|
||||
return &PlayerCache{
|
||||
func NewPlayerCache(address string, lifetime time.Duration, expireCallback func(key string)) *PlayerCache {
|
||||
pc := &PlayerCache{
|
||||
redis.NewClient(
|
||||
&redis.Options{
|
||||
Addr: address,
|
||||
@@ -25,7 +28,23 @@ func NewPlayerCache(address string, lifetime time.Duration) *PlayerCache {
|
||||
DB: 0,
|
||||
}),
|
||||
lifetime,
|
||||
nil,
|
||||
expireCallback,
|
||||
}
|
||||
pc.expireSub = pc.cache.PSubscribe(ctx, "__keyevent@0__:expired")
|
||||
|
||||
go func() {
|
||||
for {
|
||||
msg, err := pc.expireSub.ReceiveMessage(ctx)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
} else {
|
||||
pc.expireCallback(msg.Payload)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return pc
|
||||
}
|
||||
|
||||
func (pc *PlayerCache) Connect() error {
|
||||
@@ -42,13 +61,13 @@ func (pc *PlayerCache) GetValue(key string) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PlayerCache) SetValue(key string, value interface{}) error {
|
||||
return pc.cache.Set(ctx, key, value, pc.lifetime).Err()
|
||||
func (pc *PlayerCache) SetValue(key string, value interface{}, lifetime time.Duration) error {
|
||||
return pc.cache.Set(ctx, key, value, lifetime).Err()
|
||||
}
|
||||
|
||||
func (pc *PlayerCache) SetScore(playerId uint, gameTag string, score float32) error {
|
||||
key := getPlayerCacheKey(playerId, gameTag)
|
||||
return pc.SetValue(key, score)
|
||||
return pc.SetValue(key, score, pc.lifetime)
|
||||
}
|
||||
|
||||
func (pc *PlayerCache) GetScore(playerId uint, gameTag string) (float32, error) {
|
||||
@@ -104,3 +123,9 @@ func (pc *PlayerCache) PurgeCache() error {
|
||||
func getPlayerCacheKey(playerId uint, gameTag string) string {
|
||||
return fmt.Sprintf("player:%d:game:%s", playerId, gameTag)
|
||||
}
|
||||
|
||||
func (pc *PlayerCache) GetPlayerIdFromCacheKey(key string) (uint, error) {
|
||||
var playerId uint
|
||||
_, err := fmt.Sscanf(key, "player:%d:game:", &playerId)
|
||||
return playerId, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user