package diagram import ( "context" locker "modelRT/distributedlock" "github.com/redis/go-redis/v9" // "github.com/go-redis/redis" "go.uber.org/zap" ) // TODO 统一 storageClient与 rwLocker 中使用的 redis 版本 // RedisHash defines the encapsulation struct of redis hash type type RedisHash struct { ctx context.Context rwLocker *locker.RedissionRWLocker storageClient *redis.Client logger *zap.Logger } // SetRedisHashByMap define func of set redis hash by map struct func (rh *RedisHash) SetRedisHashByMap(hashKey string, fields map[string]interface{}) error { err := rh.rwLocker.WLock() if err != nil { rh.logger.Error("lock wLock by hashKey failed", zap.String("hashKey", hashKey), zap.Error(err)) return err } defer rh.rwLocker.UnWLock() err = rh.storageClient.HSet(rh.ctx, hashKey, fields).Err() if err != nil { rh.logger.Error("set hash by map failed", zap.String("hashKey", hashKey), zap.Any("fields", fields), zap.Error(err)) return err } return nil } // SetRedisHashByKV define func of set redis hash by kv struct func (rh *RedisHash) SetRedisHashByKV(hashKey string, field string, value interface{}) error { err := rh.rwLocker.WLock() if err != nil { rh.logger.Error("lock wLock by hashKey failed", zap.String("hashKey", hashKey), zap.Error(err)) return err } defer rh.rwLocker.UnWLock() err = rh.storageClient.HSet(rh.ctx, hashKey, field, value).Err() if err != nil { rh.logger.Error("set hash by kv failed", zap.String("hashKey", hashKey), zap.String("field", field), zap.Any("value", value), zap.Error(err)) return err } return nil } // HGet define func of get specified field value from redis hash by key and field name func (rh *RedisHash) HGet(hashKey string, field string) (string, error) { err := rh.rwLocker.RLock() if err != nil { rh.logger.Error("lock rLock by hashKey failed", zap.String("hashKey", hashKey), zap.Error(err)) return "", err } defer rh.rwLocker.UnRLock() result, err := rh.storageClient.HGet(rh.ctx, hashKey, field).Result() if err != nil { rh.logger.Error("set hash by kv failed", zap.String("hashKey", hashKey), zap.String("field", field), zap.Error(err)) return "", err } return result, nil } // HGetAll define func of get all filelds from redis hash by key func (rh *RedisHash) HGetAll(hashKey string) (map[string]string, error) { err := rh.rwLocker.RLock() if err != nil { rh.logger.Error("lock rLock by hashKey failed", zap.String("hashKey", hashKey), zap.Error(err)) return nil, err } defer rh.rwLocker.UnRLock() result, err := rh.storageClient.HGetAll(rh.ctx, hashKey).Result() if err != nil { rh.logger.Error("get all hash field by hash key failed", zap.String("hashKey", hashKey), zap.Error(err)) return nil, err } return result, nil }