-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_test.go
135 lines (112 loc) · 2.2 KB
/
example_test.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package ratelimiter
import (
"context"
"fmt"
"sync"
"time"
"github.com/andres-erbsen/clock"
)
func Example() {
const firstGroup = "firstGroup"
const secondGroup = "secondGroup"
rl := New(1000, WithoutSlack()).
AddGroup(firstGroup, 100, WithoutSlack()).
AddGroup(secondGroup, 200, WithoutSlack())
ch1 := make(chan string, 10)
ch2 := make(chan string, 10)
var wg sync.WaitGroup
wg.Add(2)
ctx := context.Background()
go func() {
defer wg.Done()
prev := time.Now()
for i := 0; i < 5; i++ {
now := rl.Take(ctx, firstGroup)
if i != 0 {
ch1 <- now.Sub(prev).String()
}
prev = now
}
}()
go func() {
defer wg.Done()
prev := time.Now()
for i := 0; i < 5; i++ {
now := rl.Take(ctx, secondGroup)
if i != 0 {
ch2 <- now.Sub(prev).String()
}
prev = now
}
}()
wg.Wait()
close(ch1)
close(ch2)
for v := range ch1 {
fmt.Println(v)
}
for v := range ch2 {
fmt.Println(v)
}
// Output:
// 10ms
// 10ms
// 10ms
// 10ms
// 5ms
// 5ms
// 5ms
// 5ms
}
//nolint:govet
//goland:noinspection GoTestName
func ExampleWithAnotherTimeWindow() {
const firstGroup = "firstGroup"
rl := New(1000, Per(500*time.Millisecond)).
AddGroup(firstGroup, 100, Per(500*time.Millisecond)) // 100 per half second or 200rps
ctx := context.Background()
prev := time.Now()
for i := 0; i < 10; i++ {
now := rl.Take(ctx, firstGroup)
if i > 0 {
fmt.Println(i, now.Sub(prev))
}
prev = now
}
// Output:
// 1 5ms
// 2 5ms
// 3 5ms
// 4 5ms
// 5 5ms
// 6 5ms
// 7 5ms
// 8 5ms
// 9 5ms
}
type clockDecorator struct {
clock.Clock
value string
}
func (c clockDecorator) Sleep(t time.Duration) {
fmt.Println("decorated sleep", c.value)
time.Sleep(t)
}
//nolint:govet
//goland:noinspection GoTestName
func ExampleWithClockDecorator() {
const firstGroup = "firstGroup"
cl := clockDecorator{Clock: clock.New(), value: "master"}
cl2 := clockDecorator{Clock: clock.New(), value: "group"}
rl := New(1000, WithClock(cl)).
AddGroup(firstGroup, 100, WithClock(cl2))
ctx := context.Background()
for i := 0; i < 2; i++ {
rl.Take(ctx, firstGroup)
}
// Output:
// decorated sleep master
// decorated sleep group
// decorated sleep master
// decorated sleep group
}