C#封装常用的Redis工具类

1.请先安装CSRedisCore
在这里插入图片描述
接口:

namespace Tools.Redis
{
    public interface IRedisTool
    {
        bool SetLongValue(string key, string value);
        bool SetValue(string key, string value, int outSecond);
        bool SetValue(string key, string value);
        bool Exists(string key);
        bool UpdateValue(string key, string value);
        string? GetValue(string key);
        T? GetValue<T>(string key);
        T? GetEntity<T>(string key);
        List<T>? GetLike<T>(string key);
        void DeleteKey(string key);
        void DeleteLike(string key);

    }
}

实现接口方法

using CSRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tools.Redis
{
    public class RedisTool : IRedisTool
    {
        CSRedisClient csRedis;

        public RedisTool(string redisConfig)
        {
            csRedis = new CSRedisClient(redisConfig);
            RedisHelper.Initialization(csRedis);
        }

        /// <summary>
        /// 设置长时间存在的值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetLongValue(string key, string value)
        {
            try
            {
                csRedis.Set(key, value);
                return true;
            }
            catch (Exception ex)
            {
                NLogHelper.Error("RedisDataHelper-SetValue" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 设置值,并设置清除时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="outSecond"></param>
        /// <returns></returns>
        public bool SetValue(string key, string value, int outSecond)
        {
            try
            {
                csRedis.Set(key, value, outSecond);
                return true;
            }
            catch (Exception ex)
            {
                NLogHelper.Error("RedisDataHelper-SetValue" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 设置值,存在则覆盖,并沿用之前的清除时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool SetValue(string key, string value)
        {
            try
            {
                if (csRedis.Exists(key))
                {
                    long time = csRedis.Ttl(key);
                    csRedis.Set(key, value, Convert.ToInt32(time));
                }
                else
                    csRedis.Set(key, value);

                return true;
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-SetValue[{key}-{value}]" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 是否存在key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Exists(string key)
        {
            try
            {
                return csRedis.Exists(key);
            }
            catch (Exception ex)
            {
                NLogHelper.Error("RedisDataHelper-KeyExists" + ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 更新Key,把自动注销时间设置为原来的key的时间,不存在返回false
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool UpdateValue(string key, string value)
        {
            try
            {
                if (csRedis.Exists(key))
                {
                    long time = csRedis.Ttl(key);
                    csRedis.Set(key, value, Convert.ToInt32(time));
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-SetValue[{key}-{value}]" + ex.Message);
                return false;
            }
        }


        public string? GetValue(string key)
        {
            try
            {
                return csRedis.Get(key);
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-GetValue[{key}]" + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 获得json序列化后的
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T? GetValue<T>(string key)
        {
            try
            {
                var data = csRedis.Get(key);
                return JsonConvert.DeserializeObject<T>(data);
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-GetValue[{key}]" + ex.Message);
                return default;
            }
        }

        public T? GetEntity<T>(string key)
        {
            try
            {
                var data = csRedis.Get(key);
                return JsonConvert.DeserializeObject<T>(data);
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-GetList[{key}]" + ex.Message);
                return default;
            }
        }

        public List<T>? GetLike<T>(string key)
        {
            try
            {
                var dataList = csRedis.Keys(key + "*");
                List<T> list = new List<T>();
                foreach (string item in dataList)
                {
                    var data = GetEntity<T>(item);
                    if (data != null)
                    {
                        list.Add(data);
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-GetList[{key}]" + ex.Message);
                return default;
            }
        }

        public void DeleteKey(string key)
        {
            try
            {
                csRedis.Del(key);
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-DeleteKey[{key}]" + ex.Message);
            }
        }

        public void DeleteLike(string key)
        {
            try
            {
                var dataList = csRedis.Keys(key + "*");

                foreach (string item in dataList)
                {
                    DeleteKey(item);
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error($"RedisDataHelper-DeleteLike[{key}]" + ex.Message);
            }
        }


        private bool AcquireLock(string lockKey, string lockValue, int lockTimeoutSeconds)
        {
            // 尝试获取锁
            bool lockAcquired = csRedis.SetNx(lockKey, lockValue);

            // 如果成功获取锁,设置锁的超时时间
            if (lockAcquired)
            {
                csRedis.Expire(lockKey, lockTimeoutSeconds);
            }

            return lockAcquired;
        }

        private void ReleaseLock(string lockKey, string lockValue)
        {
            // 释放锁
            // 使用 Lua 脚本确保只有持有锁的客户端才能释放锁
            string luaScript = @"
            if redis.call('get', KEYS[1]) == ARGV[1] then
                return redis.call('del', KEYS[1])
            else
                return 0
            end";

            csRedis.Eval(luaScript, lockKey, new[] { lockValue });
        }
    }
}
  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖的诗人Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值