Skip to content

Commit b6c292e

Browse files
committed
fix init cache automatically
1 parent 2edb19e commit b6c292e

File tree

3 files changed

+32
-32
lines changed

3 files changed

+32
-32
lines changed

cache/cache.go

+19-18
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"time"
66

7+
"github.com/ochom/gutils/env"
78
"github.com/ochom/gutils/helpers"
89
"github.com/redis/go-redis/v9"
910
)
@@ -22,27 +23,27 @@ var conn Cache
2223

2324
// default to memory cache
2425
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
3544
}
3645

37-
cn, err := newRedisCache(url...)
38-
if err != nil {
39-
return err
40-
}
41-
42-
conn = cn
43-
4446
go conn.cleanUp()
45-
return nil
4647
}
4748

4849
// Client ...

cache/redis.go

+6-14
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package cache
22

33
import (
44
"context"
5-
"errors"
65
"time"
76

87
"github.com/ochom/gutils/logs"
@@ -14,19 +13,12 @@ type redisCache struct {
1413
client *redis.Client
1514
}
1615

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+
})
3022
return &redisCache{
3123
client: cl,
3224
}, nil

cache/domain.go cache/types.go

+7
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,10 @@ type cacheItem struct {
2323
func (c cacheItem) expired() bool {
2424
return time.Since(c.createdAt) > c.expiry
2525
}
26+
27+
// Config ...
28+
type Config struct {
29+
Url string
30+
DbIndex int
31+
Password string
32+
}

0 commit comments

Comments
 (0)