(opt ...OptionInterface)
| 33 | } |
| 34 | |
| 35 | func NewCache[T any](opt ...OptionInterface) *Cache[T] { |
| 36 | var countPieces = 256 |
| 37 | var maxItems = 1_000_000 |
| 38 | |
| 39 | var totalMemory = memutils.SystemMemoryGB() |
| 40 | if totalMemory < 2 { |
| 41 | // 我们限制内存过小的服务能够使用的数量 |
| 42 | maxItems = 500_000 |
| 43 | } else { |
| 44 | var delta = totalMemory / 4 |
| 45 | if delta > 0 { |
| 46 | maxItems *= delta |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | for _, option := range opt { |
| 51 | if option == nil { |
| 52 | continue |
| 53 | } |
| 54 | switch o := option.(type) { |
| 55 | case *PiecesOption: |
| 56 | if o.Count > 0 { |
| 57 | countPieces = o.Count |
| 58 | } |
| 59 | case *MaxItemsOption: |
| 60 | if o.Count > 0 { |
| 61 | maxItems = o.Count |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | var maxPiecesPerGC = 4 |
| 67 | var numCPU = runtime.NumCPU() / 2 |
| 68 | if numCPU > maxPiecesPerGC { |
| 69 | maxPiecesPerGC = numCPU |
| 70 | } |
| 71 | |
| 72 | var cache = &Cache[T]{ |
| 73 | countPieces: uint64(countPieces), |
| 74 | maxItems: maxItems, |
| 75 | maxPiecesPerGC: maxPiecesPerGC, |
| 76 | } |
| 77 | |
| 78 | for i := 0; i < countPieces; i++ { |
| 79 | cache.pieces = append(cache.pieces, NewPiece[T](maxItems/countPieces)) |
| 80 | } |
| 81 | |
| 82 | // Add to manager |
| 83 | SharedManager.Add(cache) |
| 84 | |
| 85 | return cache |
| 86 | } |
| 87 | |
| 88 | func (this *Cache[T]) Write(key string, value T, expiredAt int64) (ok bool) { |
| 89 | if this.isDestroyed { |
no test coverage detected