Browse Source

[🚀] HIncr

bvbej 1 year ago
parent
commit
857f930b5a
1 changed files with 54 additions and 0 deletions
  1. 54 0
      pkg/cache/redis.go

+ 54 - 0
pkg/cache/redis.go

@@ -51,6 +51,8 @@ type Repo interface {
 	HSet(key, field, value string, options ...Option) error
 	HDel(key, field string, options ...Option) error
 	HGetAll(key string, options ...Option) (map[string]string, error)
+	HIncrBy(key, field string, incr int64, options ...Option) (int64, error)
+	HIncrByFloat(key, field string, incr float64, options ...Option) (float64, error)
 	LPush(key, value string, options ...Option) error
 	LLen(key string, options ...Option) (int64, error)
 	BRPop(key string, timeout time.Duration, options ...Option) (string, error)
@@ -346,6 +348,58 @@ func (c *cacheRepo) HGetAll(key string, options ...Option) (map[string]string, e
 	return value, nil
 }
 
+func (c *cacheRepo) HIncrBy(key, field string, incr int64, options ...Option) (int64, error) {
+	ts := time.Now()
+	opt := newOption()
+	defer func() {
+		if opt.Trace != nil {
+			opt.Redis.Timestamp = time_parse.CSTLayoutString()
+			opt.Redis.Handle = "hash incr int64"
+			opt.Redis.Key = key
+			opt.Redis.Value = fmt.Sprintf("field:%s incr:%d", field, incr)
+			opt.Redis.CostSeconds = time.Since(ts).Seconds()
+			opt.Trace.AppendRedis(opt.Redis)
+		}
+	}()
+
+	for _, f := range options {
+		f(opt)
+	}
+
+	value, err := c.client.HIncrBy(c.ctx, key, field, incr).Result()
+	if err != nil {
+		return 0, errors.Join(err, fmt.Errorf("redis hash incr int64 key: %s err", key))
+	}
+
+	return value, nil
+}
+
+func (c *cacheRepo) HIncrByFloat(key, field string, incr float64, options ...Option) (float64, error) {
+	ts := time.Now()
+	opt := newOption()
+	defer func() {
+		if opt.Trace != nil {
+			opt.Redis.Timestamp = time_parse.CSTLayoutString()
+			opt.Redis.Handle = "hash incr float64"
+			opt.Redis.Key = key
+			opt.Redis.Value = fmt.Sprintf("field:%s incr:%d", field, incr)
+			opt.Redis.CostSeconds = time.Since(ts).Seconds()
+			opt.Trace.AppendRedis(opt.Redis)
+		}
+	}()
+
+	for _, f := range options {
+		f(opt)
+	}
+
+	value, err := c.client.HIncrByFloat(c.ctx, key, field, incr).Result()
+	if err != nil {
+		return 0, errors.Join(err, fmt.Errorf("redis hash incr float64 key: %s err", key))
+	}
+
+	return value, nil
+}
+
 func (c *cacheRepo) LPush(key, value string, options ...Option) error {
 	ts := time.Now()
 	opt := newOption()