-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
114 lines (94 loc) · 2.04 KB
/
main.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
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
package main
import (
"context"
"log"
"os"
"sort"
"sync"
"time"
"golang.org/x/time/rate"
)
func main() {
defer log.Print("Done.")
log.SetOutput(os.Stdout)
log.SetFlags(log.Ltime | log.LUTC)
api := open()
var wg sync.WaitGroup
wg.Add(20)
for i := 0; i < 10; i++ {
go func(id int) {
defer wg.Done()
err := api.readFile(context.Background())
if err != nil {
log.Printf("%d cannot read file: %s", id, err)
}
log.Printf("%d read file", id)
}(i)
}
for i := 10; i < 20; i++ {
go func(id int) {
defer wg.Done()
err := api.resolveAddress(context.Background())
if err != nil {
log.Printf("%d cannot resolve address: %s", id, err)
}
log.Printf("%d resolve address", id)
}(i)
}
wg.Wait()
}
func per(eventCount int, duration time.Duration) rate.Limit {
return rate.Every(duration / time.Duration(eventCount))
}
func open() *API {
secondLimit := rate.NewLimiter(per(2, time.Second), 1)
minuteLimit := rate.NewLimiter(per(10, time.Minute), 10)
return &API{
rateLimiter: makeMultiLimiter(secondLimit, minuteLimit),
}
}
// API is Application Programming Interface
type API struct {
rateLimiter rateLimiter
}
func (a *API) readFile(ctx context.Context) error {
if err := a.rateLimiter.Wait(ctx); err != nil {
return err
}
// do something
return nil
}
func (a *API) resolveAddress(ctx context.Context) error {
if err := a.rateLimiter.Wait(ctx); err != nil {
return err
}
// do something
return nil
}
type rateLimiter interface {
Wait(context.Context) error
Limit() rate.Limit
}
type multiLimiter struct {
limiters []rateLimiter
}
func makeMultiLimiter(limiters ...rateLimiter) *multiLimiter {
byLimit := func(i, j int) bool {
return limiters[i].Limit() < limiters[j].Limit()
}
sort.Slice(limiters, byLimit)
return &multiLimiter{
limiters: limiters,
}
}
func (ml *multiLimiter) Wait(ctx context.Context) error {
for _, l := range ml.limiters {
if err := l.Wait(ctx); err != nil {
return err
}
}
return nil
}
func (ml *multiLimiter) Limit() rate.Limit {
return ml.limiters[0].Limit()
}