diff --git a/requester/tcpaddr_cache.go b/requester/tcpaddr_cache.go index 4303e4c5..877ed3f7 100644 --- a/requester/tcpaddr_cache.go +++ b/requester/tcpaddr_cache.go @@ -24,9 +24,16 @@ type tcpAddrCache struct { gcStarted bool } +// tcpAddrItem tcpAddrCache中缓存的带有超时的TcpAddr +type tcpAddrItem struct { + ta *net.TCPAddr + expire <-chan time.Time // 缓存项是否过期 +} + // Set 设置 func (tac *tcpAddrCache) Set(address string, ta *net.TCPAddr) { - tac.ta.Store(address, ta) + item := &tcpAddrItem{ta, time.After(tac.lifeTime)} + tac.ta.Store(address, item) } // Existed 检测存在 @@ -43,15 +50,21 @@ func (tac *tcpAddrCache) Existed(address string) bool { func (tac *tcpAddrCache) Get(address string) *net.TCPAddr { if tac.Existed(address) { value, _ := tac.ta.Load(address) - return value.(*net.TCPAddr) + return value.(*tcpAddrItem).ta } return nil } // SetLifeTime 设置生命周期 +// 重新设定生命周期将会影响所有的缓存项 func (tac *tcpAddrCache) SetLifeTime(t time.Duration) { tac.lifeTime = t + tac.ta.Range(func(_, v interface{}) bool { + item := v.(*tcpAddrItem) + item.expire = time.After(tac.lifeTime) + return true + }) } // GC 缓存回收 @@ -76,9 +89,15 @@ func (tac *tcpAddrCache) Del(address string) { // DelAll 清空缓存 func (tac *tcpAddrCache) DelAll() { - tac.ta.Range(func(address, _ interface{}) bool { - tac.ta.Delete(address) - return true + tac.ta.Range(func(address, v interface{}) bool { + item := v.(*tcpAddrItem) + select { + case <- item.expire: // 如果超时再删去缓存项,避免在接近lifeTime前添加的缓存项被删除 + tac.ta.Delete(address) + return true + default: + return true + } }) } @@ -87,7 +106,7 @@ func (tac *tcpAddrCache) PrintAll() { tb := pcstable.NewTable(os.Stdout) tb.SetHeader([]string{"address", "tcpaddr"}) tac.ta.Range(func(address, tcpaddr interface{}) bool { - tb.Append([]string{address.(string), fmt.Sprint(tcpaddr.(*net.TCPAddr))}) + tb.Append([]string{address.(string), fmt.Sprint(tcpaddr.(*tcpAddrItem).ta)}) return true }) tb.Render()