-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
116 lines (94 loc) · 1.84 KB
/
Copy pathmain.go
File metadata and controls
116 lines (94 loc) · 1.84 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"context"
"log"
"net"
"net/rpc"
"runtime"
"sync"
"time"
"github.com/XieGuochao/HippoCoinRegister/lib"
)
const (
// HippoAddressServiceName ...
HippoAddressServiceName = "github.com/XieGuochao/HippoCoinRegister"
// TTL ...
// The TTL is 60 seconds
TTL = 60
// MaxQuery ...
MaxQuery = 30
// MaxCycle ...
MaxCycle = 5
// NumPerCycle ...
NumPerCycle = 20
// Threshold ...
Threshold = 0.2
)
func expired(t, now int64) bool {
return now-t > TTL
}
// clearCycle
func clearCycle(ctx context.Context, c *sync.Map) {
cleared := 1
count := 1
total := 0
t := time.Now().Unix()
for float64(cleared)/float64(count) > Threshold && total < NumPerCycle {
cleared = 1
count = 1
total++
c.Range(func(key, value interface{}) bool {
select {
case <-ctx.Done():
return false
default:
{
if expired(value.(int64), t) {
c.Delete(key)
cleared++
}
count++
total++
if total > NumPerCycle {
return false
}
}
}
return true
})
}
}
// clear the outdated cache.
func clearCache(ctx context.Context, c *sync.Map) {
for i := 0; i < MaxCycle; i++ {
go clearCycle(ctx, c)
}
}
func main() {
runtime.GOMAXPROCS(4)
log.Println("register server starts...")
lib.RegisterHippoAddress(new(lib.ServiceStruct))
listener, err := net.Listen("tcp", ":9325")
if err != nil {
log.Fatal("ListenTCP error:", err)
}
log.Println("outer IP:", lib.GetOutboundIP().String())
// clear cache for every 10 seconds
go func() {
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
clearCache(ctx, &lib.Cache)
<-ctx.Done()
log.Println("clear done 1 cycle")
time.Sleep(time.Second * TTL)
cancel()
}
}()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error:", err)
}
go rpc.ServeConn(conn)
}
}