问题:存储IP地址和计时器的时间.这样的事情
ip,时间,计数
然后我希望能够增加每个ip的计数:
IP ++
在我的地图中,然后在给定的时间间隔内,我想迭代所有键并找到时间戳大于N分钟的键.
我需要这个以确保我不会"忘记"内存中的密钥如果由于某种原因,客户端断开连接并且我没有正确删除密钥.
http://play.golang.org/p/RiWWOCARq7
问题:如何为我在地图中存储的每个IP地址添加时间戳.此外,我需要在多个go例程中使用它
我是编程和Golang的新手,所以如果这甚至不是正确的方法,如果有人能指出我正确的方向,我将不胜感激.
例如,
package main
import (
"sync"
"time"
)
type IPCounter struct {
IPAddr string
Time time.Time
Count int
}
type ipCounterMap struct {
counters map[string]IPCounter
mutex sync.RWMutex
}
var ipCounters = ipCounterMap{counters: make(map[string]IPCounter)}
// Get IP address counter
func Counter(ipAddr string) IPCounter {
ipCounters.mutex.RLock()
defer ipCounters.mutex.RUnlock()
counter, found := ipCounters.counters[ipAddr]
if !found {
counter.IPAddr = ipAddr
}
return counter
}
// Increment IP address counter
func Incr(ipAddr string) {
now := time.Now().UTC()
ipCounters.mutex.Lock()
defer ipCounters.mutex.Unlock()
counter, found := ipCounters.counters[ipAddr]
if !found {
counter.IPAddr = ipAddr
}
counter.Time = now
counter.Count++
ipCounters.counters[ipAddr] = counter
}
// Delete IP address counter
func Delete(ipAddr string) {
ipCounters.mutex.Lock()
defer ipCounters.mutex.Unlock()
delete(ipCounters.counters, ipAddr)
}
// Get old IP address counters old durations ago
func OldIPCounters(old time.Duration) []IPCounter {
var counters []IPCounter
oldTime := time.Now().UTC().Add(-old)
ipCounters.mutex.RLock()
defer ipCounters.mutex.RUnlock()
for _, counter := range ipCounters.counters {
if counter.Time.Before(oldTime) {
counters = append(counters, counter)
}
}
return counters
}
func main() {}
Run Code Online (Sandbox Code Playgroud)
你可能想要一个 ip -> struct { ip, counter, lastTime } 这样的映射,你可以通过 ip 查找计数器然后更新它
var Counters = map[string]*Counter{}
type Counter struct {
ip string
count int
lastTime time.Time
}
Run Code Online (Sandbox Code Playgroud)
这是 Play http://play.golang.org/p/TlCTc_4iq5上的一个工作示例
添加比现在更旧的查找,只是在地图的值范围内与现在进行比较,并在它足够老的时候做一些事情。