Created
September 13, 2020 01:28
-
-
Save alexrios/8125a36810f78d6505fc58444237b265 to your computer and use it in GitHub Desktop.
Rate limiting with redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"time" | |
"github.com/go-redis/redis/v8" | |
"github.com/go-redis/redis_rate/v9" | |
"github.com/testcontainers/testcontainers-go" | |
"github.com/testcontainers/testcontainers-go/wait" | |
) | |
func main() { | |
ctx := context.Background() | |
req := testcontainers.ContainerRequest{ | |
Image: "redis:latest", | |
ExposedPorts: []string{"6379/tcp"}, | |
WaitingFor: wait.ForLog("Ready to accept connections"), | |
} | |
redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ | |
ContainerRequest: req, | |
Started: true, | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer redisC.Terminate(ctx) | |
endpoint, err := redisC.Endpoint(ctx, "") | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(endpoint) | |
rdb := redis.NewClient(&redis.Options{ | |
Addr: endpoint, | |
}) | |
_ = rdb.FlushDB(ctx).Err() | |
rdb.Close() | |
limiter := redis_rate.NewLimiter(rdb) | |
limit := redis_rate.PerSecond(10) | |
for i := 0; i <= 20; i++ { | |
res, err := limiter.Allow(ctx, "project:123", limit) | |
if err != nil { | |
panic(err) | |
} | |
if i > 10 && i < 15 { | |
time.Sleep(500 * time.Millisecond) | |
} | |
if i > 14 { | |
time.Sleep(1 * time.Second) | |
} | |
fmt.Println("allowed", res.Allowed, "remaining", res.Remaining) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment