Commit b6c292e 1 parent 2edb19e commit b6c292e Copy full SHA for b6c292e
File tree 3 files changed +32
-32
lines changed
3 files changed +32
-32
lines changed Original file line number Diff line number Diff line change 4
4
"fmt"
5
5
"time"
6
6
7
+ "github.com/ochom/gutils/env"
7
8
"github.com/ochom/gutils/helpers"
8
9
"github.com/redis/go-redis/v9"
9
10
)
@@ -22,27 +23,27 @@ var conn Cache
22
23
23
24
// default to memory cache
24
25
func init () {
25
- conn = newMemoryCache ()
26
-
27
- go conn .cleanUp ()
28
- }
29
-
30
- // NewCache ...
31
- func Init (driver CacheDriver , url ... string ) error {
32
- if driver == Memory {
33
- // cache is already running return nil
34
- return nil
26
+ driver := env .Get ("CACHE_DRIVER" , "memory" )
27
+ if driver == "memory" {
28
+ conn = newMemoryCache ()
29
+ } else {
30
+ url := env .Get ("REDIS_URL" , "localhost:6379" )
31
+ password := env .Get ("REDIS_PASSWORD" , "" )
32
+ dbIndex := env .Int ("REDIS_DB_INDEX" , 0 )
33
+ con , err := newRedisCache (& Config {
34
+ Url : url ,
35
+ DbIndex : dbIndex ,
36
+ Password : password ,
37
+ })
38
+
39
+ if err != nil {
40
+ panic (err )
41
+ }
42
+
43
+ conn = con
35
44
}
36
45
37
- cn , err := newRedisCache (url ... )
38
- if err != nil {
39
- return err
40
- }
41
-
42
- conn = cn
43
-
44
46
go conn .cleanUp ()
45
- return nil
46
47
}
47
48
48
49
// Client ...
Original file line number Diff line number Diff line change @@ -2,7 +2,6 @@ package cache
2
2
3
3
import (
4
4
"context"
5
- "errors"
6
5
"time"
7
6
8
7
"github.com/ochom/gutils/logs"
@@ -14,19 +13,12 @@ type redisCache struct {
14
13
client * redis.Client
15
14
}
16
15
17
- func newRedisCache (url ... string ) (Cache , error ) {
18
- if len (url ) == 0 {
19
- logs .Error ("newRedisCache: url is empty" )
20
- return nil , errors .New ("url is empty" )
21
- }
22
-
23
- opt , err := redis .ParseURL (url [0 ])
24
- if err != nil {
25
- logs .Error ("newRedisCache: %s" , err .Error ())
26
- return nil , err
27
- }
28
-
29
- cl := redis .NewClient (opt )
16
+ func newRedisCache (cfg * Config ) (Cache , error ) {
17
+ cl := redis .NewClient (& redis.Options {
18
+ Addr : cfg .Url ,
19
+ Password : cfg .Password ,
20
+ DB : cfg .DbIndex ,
21
+ })
30
22
return & redisCache {
31
23
client : cl ,
32
24
}, nil
Original file line number Diff line number Diff line change @@ -23,3 +23,10 @@ type cacheItem struct {
23
23
func (c cacheItem ) expired () bool {
24
24
return time .Since (c .createdAt ) > c .expiry
25
25
}
26
+
27
+ // Config ...
28
+ type Config struct {
29
+ Url string
30
+ DbIndex int
31
+ Password string
32
+ }
You can’t perform that action at this time.
0 commit comments