千家信息网

C#中Helper类如何使用

发表于:2024-09-30 作者:千家信息网编辑
千家信息网最后更新 2024年09月30日,本文小编为大家详细介绍"C#中Helper类如何使用",内容详细,步骤清晰,细节处理妥当,希望这篇"C#中Helper类如何使用"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧
千家信息网最后更新 2024年09月30日C#中Helper类如何使用

本文小编为大家详细介绍"C#中Helper类如何使用",内容详细,步骤清晰,细节处理妥当,希望这篇"C#中Helper类如何使用"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

    使用背景

    项目中用户频繁访问数据库会导致程序的卡顿,甚至堵塞。使用缓存可以有效的降低用户访问数据库的频次,有效的减少并发的压力。保护后端真实的服务器。

    对于开发人员需要方便调用,所以本文提供了helper类对缓存有了封装。分了三个Cache,SystemCache,RedisCache(默认缓存,系统缓存,Redis缓存)。话不多说,开撸!

    使用方法

    1.引用CSRedisCore

    可以看到,csredis支持.net40/.net45/.netstandard平台,还是比较友好的。

    2.增加helper类代码

    CacheHelper.cs

    ///     /// 缓存帮助类    ///     public class CacheHelper    {        ///         /// 静态构造函数,初始化缓存类型        ///         static CacheHelper()        {            SystemCache = new SystemCache();       if(true)       //项目全局变量类,可自行定义           // if (GlobalSwitch.OpenRedisCache)            {                try                {                    RedisCache = new RedisCache(GlobalSwitch.RedisConfig);                }                catch                {                }            }            switch (GlobalSwitch.CacheType)            {                case CacheType.SystemCache:Cache = SystemCache;break;                case CacheType.RedisCache:Cache = RedisCache;break;                default:throw new Exception("请指定缓存类型!");            }        }        ///         /// 默认缓存        ///         public static ICache Cache { get; }        ///         /// 系统缓存        ///         public static ICache SystemCache { get; }        ///         /// Redis缓存        ///         public static ICache RedisCache { get; }    }

    ICache.cs

    ///     /// 缓存操作接口类    ///     public interface ICache    {        #region 设置缓存        ///         /// 设置缓存        ///         /// 主键        /// 值        void SetCache(string key, object value);        ///         /// 设置缓存        /// 注:默认过期类型为绝对过期        ///         /// 主键        /// 值        /// 过期时间间隔        void SetCache(string key, object value, TimeSpan timeout);        ///         /// 设置缓存        /// 注:默认过期类型为绝对过期        ///         /// 主键        /// 值        /// 过期时间间隔        /// 过期类型        void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);        ///         /// 设置键失效时间        ///         /// 键值        /// 从现在起时间间隔        void SetKeyExpire(string key, TimeSpan expire);        #endregion        #region 获取缓存        ///         /// 获取缓存        ///         /// 主键        object GetCache(string key);        ///         /// 获取缓存        ///         /// 主键        /// 数据类型        T GetCache(string key) where T : class;        ///         /// 是否存在键值        ///         /// 主键        ///         bool ContainsKey(string key);        #endregion        #region 删除缓存        ///         /// 清除缓存        ///         /// 主键        void RemoveCache(string key);        #endregion    }    #region 类型定义    ///     /// 值信息    ///     public struct ValueInfoEntry    {        public string Value { get; set; }        public string TypeName { get; set; }        public TimeSpan? ExpireTime { get; set; }        public ExpireType? ExpireType { get; set; }    }    ///     /// 过期类型    ///     public enum ExpireType    {        ///         /// 绝对过期        /// 注:即自创建一段时间后就过期        ///         Absolute,        ///         /// 相对过期        /// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长        ///         Relative,    }    #endregion

    RedisCache.cs

    ///     /// Redis缓存    ///     public class RedisCache : ICache    {        ///         /// 构造函数        /// 注意:请以单例使用        ///         /// 配置字符串        public RedisCache(string config)        {            _redisCLient = new CSRedisClient(config);        }        private CSRedisClient _redisCLient { get; }        public bool ContainsKey(string key)        {            return _redisCLient.Exists(key);        }        public object GetCache(string key)        {            object value = null;            var redisValue = _redisCLient.Get(key);            if (redisValue.IsNullOrEmpty())                return null;            ValueInfoEntry valueEntry = redisValue.ToString().ToObject();            if (valueEntry.TypeName == typeof(string).AssemblyQualifiedName)                value = valueEntry.Value;            else                value = valueEntry.Value.ToObject(Type.GetType(valueEntry.TypeName));            if (valueEntry.ExpireTime != null && valueEntry.ExpireType == ExpireType.Relative)                SetKeyExpire(key, valueEntry.ExpireTime.Value);            return value;        }        public T GetCache(string key) where T : class        {            return (T)GetCache(key);        }        public void SetKeyExpire(string key, TimeSpan expire)        {            _redisCLient.Expire(key, expire);        }        public void RemoveCache(string key)        {            _redisCLient.Del(key);        }        public void SetCache(string key, object value)        {            _SetCache(key, value, null, null);        }        public void SetCache(string key, object value, TimeSpan timeout)        {            _SetCache(key, value, timeout, ExpireType.Absolute);        }        public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)        {            _SetCache(key, value, timeout, expireType);        }        private void _SetCache(string key, object value, TimeSpan? timeout, ExpireType? expireType)        {            string jsonStr = string.Empty;            if (value is string)                jsonStr = value as string;            else                jsonStr = value.ToJson();            ValueInfoEntry entry = new ValueInfoEntry            {                Value = jsonStr,                TypeName = value.GetType().AssemblyQualifiedName,                ExpireTime = timeout,                ExpireType = expireType            };            string theValue = entry.ToJson();            if (timeout == null)                _redisCLient.Set(key, theValue);            else                _redisCLient.Set(key, theValue, (int)timeout.Value.TotalSeconds);        }    }

    SystemCache.cs

    ///     /// 系统缓存帮助类    ///     public class SystemCache : ICache    {        public object GetCache(string key)        {            return HttpRuntime.Cache[key];        }        public T GetCache(string key) where T : class        {            return (T)HttpRuntime.Cache[key];        }        public bool ContainsKey(string key)        {            return GetCache(key) != null;        }        public void RemoveCache(string key)        {            HttpRuntime.Cache.Remove(key);        }        public void SetKeyExpire(string key, TimeSpan expire)        {            object value = GetCache(key);            SetCache(key, value, expire);        }        public void SetCache(string key, object value)        {            _SetCache(key, value, null, null);        }        public void SetCache(string key, object value, TimeSpan timeout)        {            _SetCache(key, value, timeout, ExpireType.Absolute);        }        public void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType)        {            _SetCache(key, value, timeout, expireType);        }        private void _SetCache(string key, object value, TimeSpan? timeout, ExpireType? expireType)        {            if (timeout == null)                HttpRuntime.Cache[key] = value;            else            {                if (expireType == ExpireType.Absolute)                {                    DateTime endTime = DateTime.Now.AddTicks(timeout.Value.Ticks);                    HttpRuntime.Cache.Insert(key, value, null, endTime, Cache.NoSlidingExpiration);                }                else                {                    HttpRuntime.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, timeout.Value);                }            }        }    }

    3.使用

    4.说明

    Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。  

    它是基于高性能的Key-Value、并提供多种语言的 API的非关系型数据库。不过与传统数据库不同的是 redis 的数据是存在内存中的,所以存写速度非常快。

    它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets)

    读到这里,这篇"C#中Helper类如何使用"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。

    0