Skip to content

Commit

Permalink
refactor(usercache): set custom ttl for cache
Browse files Browse the repository at this point in the history
  • Loading branch information
olexsmir committed Oct 24, 2024
1 parent 4f17e84 commit 11d547e
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 5 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ POSTGRESQL_DSN="postgres://$POSTGRES_USERNAME:$POSTGRES_PASSWORD@$POSTGRES_HOST:
MIGRATION_DSN="postgres://$POSTGRES_USERNAME:$POSTGRES_PASSWORD@localhost:$POSTGRES_PORT/$POSTGRES_DATABASE?sslmode=disable"

REDIS_ADDR="redis:6379"
CACHE_USERS_TTL=1h

MAILGUN_FROM=onasty@mail.com
MAILGUN_DOMAI='<domain>'
Expand Down
2 changes: 1 addition & 1 deletion cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func run(ctx context.Context) error {
vertokrepo := vertokrepo.New(psqlDB)

userepo := userepo.New(psqlDB)
usercache := usercache.New(rdb)
usercache := usercache.New(rdb, cfg.CacheUsersTTL)
usersrv := usersrv.New(
userepo,
sessionrepo,
Expand Down
4 changes: 4 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ type Config struct {
RateLimiterRPS int
RateLimiterBurst int
RateLimiterTTL time.Duration

CacheUsersTTL time.Duration
}

func NewConfig() *Config {
Expand Down Expand Up @@ -75,6 +77,8 @@ func NewConfig() *Config {
RateLimiterRPS: mustGetenvOrDefaultInt("RATELIMITER_RPS", 100),
RateLimiterBurst: mustGetenvOrDefaultInt("RATELIMITER_BURST", 10),
RateLimiterTTL: mustParseDuration(getenvOrDefault("RATELIMITER_TTL", "1m")),

CacheUsersTTL: mustParseDuration(getenvOrDefault("CACHE_USERS_TTL", "1h")),
}
}

Expand Down
12 changes: 8 additions & 4 deletions internal/store/rdb/usercache/usercache.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,19 @@ var _ UserCacheer = (*UserCache)(nil)

type UserCache struct {
rdb *redis.Client
ttl time.Duration
}

func New(rdb *redis.Client) *UserCache {
return &UserCache{rdb}
func New(rdb *redis.Client, ttl time.Duration) *UserCache {
return &UserCache{
rdb: rdb,
ttl: ttl,
}
}

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

func (u *UserCache) SetUserIsActivated(ctx context.Context, userID string, val bool) error {
_, err := u.rdb.
Set(ctx, getKey("activated", userID), val, time.Hour).
Set(ctx, getKey("activated", userID), val, u.ttl).
Result()
return err
}
Expand Down

0 comments on commit 11d547e

Please sign in to comment.