add periodical cache expired check

This commit is contained in:
Sergey Chubaryan 2024-08-17 15:51:52 +03:00
parent df479f79be
commit 66250f7122
2 changed files with 39 additions and 1 deletions

17
main.go
View File

@ -22,6 +22,7 @@ import (
"os/signal" "os/signal"
"runtime/pprof" "runtime/pprof"
"syscall" "syscall"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/jackc/pgx" "github.com/jackc/pgx"
@ -98,10 +99,24 @@ func main() {
jwtUtil := utils.NewJwtUtil(key) jwtUtil := utils.NewJwtUtil(key)
passwordUtil := utils.NewPasswordUtil() passwordUtil := utils.NewPasswordUtil()
userRepo := repos.NewUserRepo(sqlDb) userRepo := repos.NewUserRepo(sqlDb)
userCache := repos.NewCacheInmem[string, models.UserDTO](60 * 60)
emailRepo := repos.NewEmailRepo() emailRepo := repos.NewEmailRepo()
actionTokenRepo := repos.NewActionTokenRepo(sqlDb) 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() clientNotifier := client_notifier.NewBasicNotifier()
userService := services.NewUserService( userService := services.NewUserService(

View File

@ -9,6 +9,7 @@ type Cache[K comparable, V any] interface {
Get(key K) (V, bool) Get(key K) (V, bool)
Set(key K, value V, ttlSeconds int) Set(key K, value V, ttlSeconds int)
Del(key K) Del(key K)
CheckExpired()
} }
func NewCacheInmem[K comparable, V any](ttlSeconds int) Cache[K, V] { 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) 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
}
}
}