Skip to content

Commit 11de46d

Browse files
committed
refactor(usercache): set custom ttl in redis
1 parent 4f17e84 commit 11de46d

File tree

4 files changed

+14
-5
lines changed

4 files changed

+14
-5
lines changed

.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ POSTGRESQL_DSN="postgres://$POSTGRES_USERNAME:$POSTGRES_PASSWORD@$POSTGRES_HOST:
2121
MIGRATION_DSN="postgres://$POSTGRES_USERNAME:$POSTGRES_PASSWORD@localhost:$POSTGRES_PORT/$POSTGRES_DATABASE?sslmode=disable"
2222

2323
REDIS_ADDR="redis:6379"
24+
CACHE_USERS_TTL=1h
2425

2526
MAILGUN_FROM=onasty@mail.com
2627
MAILGUN_DOMAI='<domain>'

cmd/server/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ func run(ctx context.Context) error {
7676
vertokrepo := vertokrepo.New(psqlDB)
7777

7878
userepo := userepo.New(psqlDB)
79-
usercache := usercache.New(rdb)
79+
usercache := usercache.New(rdb, cfg.CacheUsersTTL)
8080
usersrv := usersrv.New(
8181
userepo,
8282
sessionrepo,

internal/config/config.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ type Config struct {
3737
RateLimiterRPS int
3838
RateLimiterBurst int
3939
RateLimiterTTL time.Duration
40+
41+
CacheUsersTTL time.Duration
4042
}
4143

4244
func NewConfig() *Config {
@@ -75,6 +77,8 @@ func NewConfig() *Config {
7577
RateLimiterRPS: mustGetenvOrDefaultInt("RATELIMITER_RPS", 100),
7678
RateLimiterBurst: mustGetenvOrDefaultInt("RATELIMITER_BURST", 10),
7779
RateLimiterTTL: mustParseDuration(getenvOrDefault("RATELIMITER_TTL", "1m")),
80+
81+
CacheUsersTTL: mustParseDuration(getenvOrDefault("CACHE_USERS_TTL", "1h")),
7882
}
7983
}
8084

internal/store/rdb/usercache/usercache.go

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,19 @@ var _ UserCacheer = (*UserCache)(nil)
2121

2222
type UserCache struct {
2323
rdb *redis.Client
24+
ttl time.Duration
2425
}
2526

26-
func New(rdb *redis.Client) *UserCache {
27-
return &UserCache{rdb}
27+
func New(rdb *redis.Client, ttl time.Duration) *UserCache {
28+
return &UserCache{
29+
rdb: rdb,
30+
ttl: ttl,
31+
}
2832
}
2933

3034
func (u *UserCache) SetUserIsExists(ctx context.Context, userID string, val bool) error {
3135
_, err := u.rdb.
32-
Set(ctx, getKey("exists", userID), val, time.Hour).
36+
Set(ctx, getKey("exists", userID), val, u.ttl).
3337
Result()
3438
return err
3539
}
@@ -46,7 +50,7 @@ func (u *UserCache) GetUserIsExists(ctx context.Context, userID string) (bool, e
4650

4751
func (u *UserCache) SetUserIsActivated(ctx context.Context, userID string, val bool) error {
4852
_, err := u.rdb.
49-
Set(ctx, getKey("activated", userID), val, time.Hour).
53+
Set(ctx, getKey("activated", userID), val, u.ttl).
5054
Result()
5155
return err
5256
}

0 commit comments

Comments
 (0)