-
Notifications
You must be signed in to change notification settings - Fork 0
/
limiter.go
46 lines (40 loc) · 863 Bytes
/
limiter.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
package limiter
import (
"fmt"
"log"
"time"
"github.com/czhj/ahfs/modules/setting"
"github.com/go-redis/redis"
"go.uber.org/zap"
)
var (
limiter Limiter
)
func NewContext() {
if limiter == nil && setting.CacheService.Enabled {
if err := newLimiter(setting.CacheService.Cache); err != nil {
log.Fatal("Failed to initialize limiter", zap.Error(err))
}
}
}
func newLimiter(config setting.Cache) error {
switch config.Adapter {
case "redis":
options, err := redis.ParseURL(config.Url)
if err != nil {
return err
}
limiter, err = NewRedisLimiter(options)
if err != nil {
return err
}
case "memory":
limiter = NewMemoryLimiter()
default:
return fmt.Errorf("Unknow adapter [%s]", config.Adapter)
}
return nil
}
func Request(key string, count int, d time.Duration) (int, error) {
return limiter.Request(key, count, d)
}