Skip to content

Commit 7ed01a5

Browse files
author
augustus
committed
[fixed window]: add redis
1 parent 25990b1 commit 7ed01a5

12 files changed

+53
-525
lines changed

fixed_window_counter.go

Lines changed: 0 additions & 45 deletions
This file was deleted.

fixed_window_counter_test.go

Lines changed: 0 additions & 29 deletions
This file was deleted.
Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
1-
package algorithms
1+
package algorithms
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"sync"
7+
"time"
8+
9+
"github.com/redis/go-redis/v9"
10+
)
11+
12+
type FixedWindow struct {
13+
client *redis.Client
14+
window time.Duration
15+
limit int
16+
mu sync.Mutex
17+
}
18+
19+
func NewFixedWindow(client *redis.Client, window time.Duration, limit int) *FixedWindow {
20+
return &FixedWindow{
21+
client: client,
22+
window: window,
23+
limit: limit,
24+
}
25+
}
26+
27+
func (fw *FixedWindow) Allow(ctx context.Context, key string) (bool, error) {
28+
fw.mu.Lock()
29+
defer fw.mu.Unlock()
30+
31+
currentTime := time.Now().Unix()
32+
33+
windowStart := currentTime - (currentTime % int64(fw.window.Seconds()))
34+
35+
redisKey := fmt.Sprintf("fw:%s:%d", key, windowStart)
36+
37+
pipe := fw.client.TxPipeline()
38+
39+
count := pipe.Incr(ctx, redisKey)
40+
41+
pipe.Expire(ctx, redisKey, fw.window)
42+
43+
_, err := pipe.Exec(ctx)
44+
if err != nil {
45+
return false, err
46+
}
47+
48+
if count.Val() > int64(fw.limit) {
49+
return false, nil
50+
}
51+
52+
return true, nil
53+
}

leakybucket.go

Lines changed: 0 additions & 48 deletions
This file was deleted.

leakybucket_test.go

Lines changed: 0 additions & 60 deletions
This file was deleted.

main.go

Lines changed: 0 additions & 1 deletion
This file was deleted.

sliding_window_counter.go

Lines changed: 0 additions & 52 deletions
This file was deleted.

sliding_window_counter_test.go

Lines changed: 0 additions & 62 deletions
This file was deleted.

0 commit comments

Comments
 (0)