Skip to content

Commit

Permalink
improve AddIP
Browse files Browse the repository at this point in the history
  • Loading branch information
hossinasaadi committed Aug 5, 2024
1 parent f2d3d0d commit ac7d3e2
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
35 changes: 18 additions & 17 deletions app/stats/online_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,20 @@ import (

// OnlineMap is an implementation of stats.OnlineMap.
type OnlineMap struct {
value int
ipList map[string]time.Time
access sync.RWMutex
value int
ipList map[string]time.Time
access sync.RWMutex
lastCleanup time.Time
cleanupPeriod time.Duration
}

// NewOnlineMap creates a new instance of OnlineMap.
func NewOnlineMap() *OnlineMap {
return &OnlineMap{
ipList: make(map[string]time.Time),
lastCleanup: time.Now(),
cleanupPeriod: 10 * time.Second,
}
}

// Count implements stats.OnlineMap.
Expand All @@ -26,10 +37,6 @@ func (c *OnlineMap) List() []string {
func (c *OnlineMap) AddIP(ip string) {
list := c.ipList

keys := c.GetKeys()
if list == nil {
list = map[string]time.Time{}
}
if ip == "127.0.0.1" {
return
}
Expand All @@ -38,7 +45,10 @@ func (c *OnlineMap) AddIP(ip string) {
list[ip] = time.Now()
c.access.Unlock()
}
list = c.RemoveExpiredIPs(list)
if time.Since(c.lastCleanup) > c.cleanupPeriod {
list = c.RemoveExpiredIPs(list)
c.lastCleanup = time.Now()
}

c.value = len(list)
c.ipList = list
Expand Down Expand Up @@ -68,12 +78,3 @@ func (c *OnlineMap) RemoveExpiredIPs(list map[string]time.Time) map[string]time.
}
return list
}

func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
2 changes: 1 addition & 1 deletion app/stats/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (m *Manager) RegisterOnlineMap(name string) (stats.OnlineMap, error) {
return nil, errors.New("onlineMap ", name, " already registered.")
}
errors.LogDebug(context.Background(), "create new onlineMap ", name)
om := new(OnlineMap)
om := NewOnlineMap()
m.onlineMap[name] = om
return om, nil
}
Expand Down

0 comments on commit ac7d3e2

Please sign in to comment.