]> 127.0.0.1 Git - part/.git/commitdiff
add
authorqydysky <qydysky@foxmail.com>
Thu, 25 May 2023 17:42:04 +0000 (01:42 +0800)
committerqydysky <qydysky@foxmail.com>
Thu, 25 May 2023 17:42:04 +0000 (01:42 +0800)
sync/Map.go
web/Web.go

index 67c2ebb1e13c88113dd76a2657b779ecd510a4b3..b74cef136f82a1e82739e5f555635aa723fa2446 100644 (file)
@@ -99,7 +99,11 @@ func (t *MapExceeded[K, V]) Range(f func(key K, value *V) bool) {
        })
 }
 
-func (t *MapExceeded[K, V]) GC(dur ...time.Duration) {
+func (t *MapExceeded[K, V]) Len() int {
+       return t.m.Len()
+}
+
+func (t *MapExceeded[K, V]) GC() {
        t.m.Range(func(key, value any) bool {
                if value.(mapExceededItem[V]).exceeded.Before(time.Now()) {
                        t.Delete(key.(K))
index ec17ac883d836ac951e9ca2aec3417aed3309783..919d3a0bc6f896e876b2065f34647d89158f9435 100644 (file)
@@ -7,6 +7,7 @@ import (
        "strconv"
        "strings"
        "sync"
+       "sync/atomic"
        "time"
 
        psync "github.com/qydysky/part/sync"
@@ -224,7 +225,8 @@ func (t *CountLimits) AddCount(r *http.Request) (isOverflow bool) {
 }
 
 type Cache struct {
-       g psync.MapExceeded[string, []byte]
+       g   psync.MapExceeded[string, []byte]
+       gcL atomic.Int64
 }
 
 func (t *Cache) IsCache(key string) (res *[]byte, isCache bool) {
@@ -233,6 +235,10 @@ func (t *Cache) IsCache(key string) (res *[]byte, isCache bool) {
 
 func (t *Cache) Store(key string, aliveDur time.Duration, data []byte) {
        t.g.Store(key, data, aliveDur)
+       if s := int64(t.g.Len()); s > 10 && t.gcL.Load() <= s {
+               t.gcL.Store(s * 2)
+               t.g.GC()
+       }
 }
 
 func Easy_boot() *Web {