modelRT/diagram/redis_hash.go

95 lines
2.9 KiB
Go
Raw Permalink Normal View History

package diagram
import (
"context"
locker "modelRT/distributedlock"
"modelRT/logger"
"github.com/redis/go-redis/v9"
)
// RedisHash defines the encapsulation struct of redis hash type
type RedisHash struct {
ctx context.Context
rwLocker *locker.RedissionRWLocker
storageClient *redis.Client
}
// NewRedisHash define func of new redis hash instance
func NewRedisHash(ctx context.Context, hashKey string, token string, lockLeaseTime uint64, needRefresh bool) *RedisHash {
return &RedisHash{
ctx: ctx,
rwLocker: locker.InitRWLocker(hashKey, token, lockLeaseTime, needRefresh),
storageClient: GetRedisClientInstance(),
}
}
// 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(rh.ctx)
if err != nil {
logger.Error(rh.ctx, "lock wLock by hash_key failed", "hash_key", hashKey, "error", err)
return err
}
defer rh.rwLocker.UnWLock(rh.ctx)
err = rh.storageClient.HSet(rh.ctx, hashKey, fields).Err()
if err != nil {
logger.Error(rh.ctx, "set hash by map failed", "hash_key", hashKey, "fields", fields, "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(rh.ctx)
if err != nil {
logger.Error(rh.ctx, "lock wLock by hash_key failed", "hash_key", hashKey, "error", err)
return err
}
defer rh.rwLocker.UnWLock(rh.ctx)
err = rh.storageClient.HSet(rh.ctx, hashKey, field, value).Err()
if err != nil {
logger.Error(rh.ctx, "set hash by kv failed", "hash_key", hashKey, "field", field, "value", value, "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(rh.ctx)
if err != nil {
logger.Error(rh.ctx, "lock rLock by hash_key failed", "hash_key", hashKey, "error", err)
return "", err
}
defer rh.rwLocker.UnRLock(rh.ctx)
result, err := rh.storageClient.HGet(rh.ctx, hashKey, field).Result()
if err != nil {
logger.Error(rh.ctx, "set hash by kv failed", "hash_key", hashKey, "field", field, "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(rh.ctx)
if err != nil {
logger.Error(rh.ctx, "lock rLock by hash_key failed", "hash_key", hashKey, "error", err)
return nil, err
}
defer rh.rwLocker.UnRLock(rh.ctx)
result, err := rh.storageClient.HGetAll(rh.ctx, hashKey).Result()
if err != nil {
logger.Error(rh.ctx, "get all hash field by hash key failed", "hash_key", hashKey, "error", err)
return nil, err
}
return result, nil
}