Skip to content

Commit

Permalink
修改tcpAddrCache的GC机制,避免在lifeTime到达前添加并且未超时的缓存被不必要的清理。
Browse files Browse the repository at this point in the history
  • Loading branch information
apocelipes committed May 23, 2018
1 parent 6ab5bc4 commit 16d5600
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions requester/tcpaddr_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 检测存在
Expand All @@ -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 缓存回收
Expand All @@ -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
}
})
}

Expand All @@ -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()
Expand Down

0 comments on commit 16d5600

Please sign in to comment.