add periodical cache expired check
This commit is contained in:
parent
df479f79be
commit
66250f7122
17
main.go
17
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(
|
||||
|
||||
@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user