-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing_table.go
70 lines (57 loc) · 1.13 KB
/
routing_table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package router
import (
"sync"
"time"
)
type RoutingEntry struct {
tag string
err error
expire time.Time
}
func (this *RoutingEntry) Extend() {
this.expire = time.Now().Add(time.Hour)
}
func (this *RoutingEntry) Expired() bool {
return this.expire.Before(time.Now())
}
type RoutingTable struct {
sync.RWMutex
table map[string]*RoutingEntry
}
func NewRoutingTable() *RoutingTable {
return &RoutingTable{
table: make(map[string]*RoutingEntry),
}
}
func (this *RoutingTable) Cleanup() {
this.Lock()
defer this.Unlock()
for key, value := range this.table {
if value.Expired() {
delete(this.table, key)
}
}
}
func (this *RoutingTable) Set(destination string, tag string, err error) {
this.Lock()
defer this.Unlock()
entry := &RoutingEntry{
tag: tag,
err: err,
}
entry.Extend()
this.table[destination] = entry
if len(this.table) > 1000 {
go this.Cleanup()
}
}
func (this *RoutingTable) Get(destination string) (bool, string, error) {
this.RLock()
defer this.RUnlock()
entry, found := this.table[destination]
if !found {
return false, "", nil
}
entry.Extend()
return true, entry.tag, entry.err
}