@@ -40,6 +40,7 @@ func NewRedisLimitCounter(cfg *Config) (*redisCounter, error) {
40
40
cfg .PrefixKey = "httprate"
41
41
}
42
42
if cfg .FallbackTimeout == 0 {
43
+ // Activate local in-memory fallback fairly quickly, as this would slow down all requests.
43
44
cfg .FallbackTimeout = 50 * time .Millisecond
44
45
}
45
46
@@ -50,29 +51,30 @@ func NewRedisLimitCounter(cfg *Config) (*redisCounter, error) {
50
51
rc .fallbackCounter = httprate .NewLocalLimitCounter (cfg .WindowLength )
51
52
}
52
53
53
- var maxIdle , maxActive = cfg .MaxIdle , cfg .MaxActive
54
- if maxIdle <= 0 {
55
- maxIdle = 20
56
- }
57
- if maxActive <= 0 {
58
- maxActive = 50
59
- }
54
+ if cfg .Client == nil {
55
+ maxIdle , maxActive := cfg .MaxIdle , cfg .MaxActive
56
+ if maxIdle < 1 {
57
+ maxIdle = 20
58
+ }
59
+ if maxActive < 1 {
60
+ maxActive = 50
61
+ }
60
62
61
- address := fmt .Sprintf ("%s:%d" , cfg .Host , cfg .Port )
62
- rc .client = redis .NewClient (& redis.Options {
63
- Addr : address ,
64
- Password : cfg .Password ,
65
- DB : cfg .DBIndex ,
66
- PoolSize : maxActive ,
67
- MaxIdleConns : maxIdle ,
68
- ClientName : cfg .ClientName ,
63
+ rc .client = redis .NewClient (& redis.Options {
64
+ Addr : fmt .Sprintf ("%s:%d" , cfg .Host , cfg .Port ),
65
+ Password : cfg .Password ,
66
+ DB : cfg .DBIndex ,
67
+ ClientName : cfg .ClientName ,
69
68
70
- DialTimeout : cfg .FallbackTimeout ,
71
- ReadTimeout : cfg .FallbackTimeout ,
72
- WriteTimeout : cfg .FallbackTimeout ,
73
- MinIdleConns : 1 ,
74
- MaxRetries : - 1 ,
75
- })
69
+ DialTimeout : cfg .FallbackTimeout ,
70
+ ReadTimeout : cfg .FallbackTimeout ,
71
+ WriteTimeout : cfg .FallbackTimeout ,
72
+ PoolSize : maxActive ,
73
+ MinIdleConns : 1 ,
74
+ MaxIdleConns : maxIdle ,
75
+ MaxRetries : - 1 , // -1 disables retries
76
+ })
77
+ }
76
78
77
79
return rc , nil
78
80
}
@@ -109,7 +111,7 @@ func (c *redisCounter) IncrementBy(key string, currentWindow time.Time, amount i
109
111
var netErr net.Error
110
112
if errors .As (err , & netErr ) || errors .Is (err , redis .ErrClosed ) {
111
113
go c .fallback ()
112
- err = c .fallbackCounter .IncrementBy (key , currentWindow , amount ) // = nil
114
+ err = c .fallbackCounter .IncrementBy (key , currentWindow , amount )
113
115
}
114
116
}
115
117
}()
0 commit comments