github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/agents/ip_cache_map.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
     2  
     3  package agents
     4  
     5  import (
     6  	"github.com/TeaOSLab/EdgeNode/internal/zero"
     7  	"sync"
     8  )
     9  
    10  type IPCacheMap struct {
    11  	m    map[string]zero.Zero
    12  	list []string
    13  
    14  	locker sync.RWMutex
    15  	maxLen int
    16  }
    17  
    18  func NewIPCacheMap(maxLen int) *IPCacheMap {
    19  	if maxLen <= 0 {
    20  		maxLen = 65535
    21  	}
    22  	return &IPCacheMap{
    23  		m:      map[string]zero.Zero{},
    24  		maxLen: maxLen,
    25  	}
    26  }
    27  
    28  func (this *IPCacheMap) Add(ip string) {
    29  	this.locker.Lock()
    30  	defer this.locker.Unlock()
    31  
    32  	// 是否已经存在
    33  	_, ok := this.m[ip]
    34  	if ok {
    35  		return
    36  	}
    37  
    38  	// 超出长度删除第一个
    39  	if len(this.list) >= this.maxLen {
    40  		delete(this.m, this.list[0])
    41  		this.list = this.list[1:]
    42  	}
    43  
    44  	// 加入新数据
    45  	this.m[ip] = zero.Zero{}
    46  	this.list = append(this.list, ip)
    47  }
    48  
    49  func (this *IPCacheMap) Contains(ip string) bool {
    50  	this.locker.RLock()
    51  	defer this.locker.RUnlock()
    52  	_, ok := this.m[ip]
    53  	return ok
    54  }