From 66250f7122acbb8b7ca092f5d2f3cbf66e956705 Mon Sep 17 00:00:00 2001 From: Sergey Chubaryan Date: Sat, 17 Aug 2024 15:51:52 +0300 Subject: [PATCH] add periodical cache expired check --- main.go | 17 ++++++++++++++++- src/core/repos/cache_inmem.go | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index 40f1820..dff4fd9 100644 --- a/main.go +++ b/main.go @@ -22,6 +22,7 @@ import ( "os/signal" "runtime/pprof" "syscall" + "time" "github.com/gin-gonic/gin" "github.com/jackc/pgx" @@ -98,10 +99,24 @@ func main() { jwtUtil := utils.NewJwtUtil(key) passwordUtil := utils.NewPasswordUtil() userRepo := repos.NewUserRepo(sqlDb) - userCache := repos.NewCacheInmem[string, models.UserDTO](60 * 60) emailRepo := repos.NewEmailRepo() actionTokenRepo := repos.NewActionTokenRepo(sqlDb) + userCache := repos.NewCacheInmem[string, models.UserDTO](60 * 60) + go func() { + tmr := time.NewTicker(30 * time.Second) + defer tmr.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-tmr.C: + userCache.CheckExpired() + } + } + }() + clientNotifier := client_notifier.NewBasicNotifier() userService := services.NewUserService( diff --git a/src/core/repos/cache_inmem.go b/src/core/repos/cache_inmem.go index 4b834ca..6503c3e 100644 --- a/src/core/repos/cache_inmem.go +++ b/src/core/repos/cache_inmem.go @@ -9,6 +9,7 @@ type Cache[K comparable, V any] interface { Get(key K) (V, bool) Set(key K, value V, ttlSeconds int) Del(key K) + CheckExpired() } func NewCacheInmem[K comparable, V any](ttlSeconds int) Cache[K, V] { @@ -74,3 +75,25 @@ func (c *cacheInmem[K, V]) Del(key K) { delete(c.data, key) } + +func (c *cacheInmem[K, V]) CheckExpired() { + if len(c.data) == 0 { + return + } + + c.m.Lock() + defer c.m.Unlock() + + itemsToProcess := 1000 + for key, item := range c.data { + timestamp := time.Now().Unix() + if item.Expiration <= timestamp { + delete(c.data, key) + } + + itemsToProcess-- + if itemsToProcess <= 0 { + return + } + } +}