| 1 |
package goredisstore_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"log" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/go-redis/redis" |
| 9 |
"github.com/throttled/throttled" |
| 10 |
"github.com/throttled/throttled/store/goredisstore" |
| 11 |
"github.com/throttled/throttled/store/storetest" |
| 12 |
) |
| 13 |
|
| 14 |
const ( |
| 15 |
redisTestDB = 1 |
| 16 |
redisTestPrefix = "throttled-go-redis:" |
| 17 |
) |
| 18 |
|
| 19 |
// Demonstrates that how to initialize a RateLimiter with redis |
| 20 |
// using go-redis library. |
| 21 |
func ExampleNew() { |
| 22 |
// import "github.com/go-redis/redis" |
| 23 |
|
| 24 |
// Initialize a redis client using go-redis |
| 25 |
client := redis.NewClient(&redis.Options{ |
| 26 |
PoolSize: 10, // default |
| 27 |
IdleTimeout: 30 * time.Second, |
| 28 |
Addr: "localhost:6379", |
| 29 |
Password: "", // no password set |
| 30 |
DB: 0, // use default DB |
| 31 |
}) |
| 32 |
|
| 33 |
// Setup store |
| 34 |
store, err := goredisstore.New(client, "throttled:") |
| 35 |
if err != nil { |
| 36 |
log.Fatal(err) |
| 37 |
} |
| 38 |
|
| 39 |
// Setup quota |
| 40 |
quota := throttled.RateQuota{MaxRate: throttled.PerMin(20), MaxBurst: 5} |
| 41 |
|
| 42 |
// Then, use store and quota as arguments for NewGCRARateLimiter() |
| 43 |
throttled.NewGCRARateLimiter(store, quota) |
| 44 |
} |
| 45 |
|
| 46 |
func TestRedisStore(t *testing.T) { |
| 47 |
c, st := setupRedis(t, 0) |
| 48 |
defer c.Close() |
| 49 |
defer clearRedis(c) |
| 50 |
|
| 51 |
clearRedis(c) |
| 52 |
storetest.TestGCRAStore(t, st) |
| 53 |
storetest.TestGCRAStoreTTL(t, st) |
| 54 |
} |
| 55 |
|
| 56 |
func BenchmarkRedisStore(b *testing.B) { |
| 57 |
c, st := setupRedis(b, 0) |
| 58 |
defer c.Close() |
| 59 |
defer clearRedis(c) |
| 60 |
|
| 61 |
storetest.BenchmarkGCRAStore(b, st) |
| 62 |
} |
| 63 |
|
| 64 |
func clearRedis(c *redis.Client) error { |
| 65 |
keys, err := c.Keys(redisTestPrefix + "*").Result() |
| 66 |
if err != nil { |
| 67 |
return err |
| 68 |
} |
| 69 |
|
| 70 |
return c.Del(keys...).Err() |
| 71 |
} |
| 72 |
|
| 73 |
func setupRedis(tb testing.TB, ttl time.Duration) (*redis.Client, *goredisstore.GoRedisStore) { |
| 74 |
client := redis.NewClient(&redis.Options{ |
| 75 |
PoolSize: 10, // default |
| 76 |
IdleTimeout: 30 * time.Second, |
| 77 |
Addr: "localhost:6379", |
| 78 |
Password: "", // no password set |
| 79 |
DB: redisTestDB, // use default DB |
| 80 |
}) |
| 81 |
|
| 82 |
if err := client.Ping().Err(); err != nil { |
| 83 |
client.Close() |
| 84 |
tb.Skip("redis server not available on localhost port 6379") |
| 85 |
} |
| 86 |
|
| 87 |
st, err := goredisstore.New(client, redisTestPrefix) |
| 88 |
if err != nil { |
| 89 |
client.Close() |
| 90 |
tb.Fatal(err) |
| 91 |
} |
| 92 |
|
| 93 |
return client, st |
| 94 |
} |