Initial cloud-services repo - gateway service + pkg modules
This commit is contained in:
45
pkg/logger/limiter.go
Normal file
45
pkg/logger/limiter.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ReneKroon/ttlcache/v2"
|
||||
)
|
||||
|
||||
func NewLogLimiter(duration time.Duration, limit int) *LogLimiter {
|
||||
return &LogLimiter{
|
||||
duration: duration,
|
||||
limit: limit,
|
||||
}
|
||||
}
|
||||
|
||||
type LogLimiter struct {
|
||||
duration time.Duration
|
||||
limit int
|
||||
cache *ttlcache.Cache
|
||||
onceCache sync.Once
|
||||
}
|
||||
|
||||
func (l *LogLimiter) Check(message string) bool {
|
||||
_, err := l.logCache().Get(message)
|
||||
if err == ttlcache.ErrNotFound {
|
||||
l.logCache().Set(message, true)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (l *LogLimiter) logCache() *ttlcache.Cache {
|
||||
l.onceCache.Do(func() {
|
||||
if l.cache == nil {
|
||||
cache := ttlcache.NewCache()
|
||||
cache.SetTTL(l.duration)
|
||||
cache.SetCacheSizeLimit(l.limit)
|
||||
l.cache = cache
|
||||
}
|
||||
})
|
||||
|
||||
return l.cache
|
||||
}
|
||||
Reference in New Issue
Block a user