当前位置:主页 > 软件编程 > .NET代码 >

详解C#中Helper类的使用

时间:2022-12-12 10:15:43 | 栏目:.NET代码 | 点击:

使用背景

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

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

使用方法

1.引用CSRedisCore

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

2.增加helper类代码

CacheHelper.cs

/// <summary>
    /// 缓存帮助类
    /// </summary>
    public class CacheHelper
    {
        /// <summary>
        /// 静态构造函数,初始化缓存类型
        /// </summary>
        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("请指定缓存类型!");
            }
        }

        /// <summary>
        /// 默认缓存
        /// </summary>
        public static ICache Cache { get; }

        /// <summary>
        /// 系统缓存
        /// </summary>
        public static ICache SystemCache { get; }

        /// <summary>
        /// Redis缓存
        /// </summary>
        public static ICache RedisCache { get; }
    }

ICache.cs

/// <summary>
    /// 缓存操作接口类
    /// </summary>
    public interface ICache
    {
        #region 设置缓存

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key">主键</param>
        /// <param name="value">值</param>
        void SetCache(string key, object value);

        /// <summary>
        /// 设置缓存
        /// 注:默认过期类型为绝对过期
        /// </summary>
        /// <param name="key">主键</param>
        /// <param name="value">值</param>
        /// <param name="timeout">过期时间间隔</param>
        void SetCache(string key, object value, TimeSpan timeout);

        /// <summary>
        /// 设置缓存
        /// 注:默认过期类型为绝对过期
        /// </summary>
        /// <param name="key">主键</param>
        /// <param name="value">值</param>
        /// <param name="timeout">过期时间间隔</param>
        /// <param name="expireType">过期类型</param>
        void SetCache(string key, object value, TimeSpan timeout, ExpireType expireType);

        /// <summary>
        /// 设置键失效时间
        /// </summary>
        /// <param name="key">键值</param>
        /// <param name="expire">从现在起时间间隔</param>
        void SetKeyExpire(string key, TimeSpan expire);

        #endregion

        #region 获取缓存

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">主键</param>
        object GetCache(string key);

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">主键</param>
        /// <typeparam name="T">数据类型</typeparam>
        T GetCache<T>(string key) where T : class;

        /// <summary>
        /// 是否存在键值
        /// </summary>
        /// <param name="key">主键</param>
        /// <returns></returns>
        bool ContainsKey(string key);

        #endregion

        #region 删除缓存

        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="key">主键</param>
        void RemoveCache(string key);

        #endregion
    }

    #region 类型定义

    /// <summary>
    /// 值信息
    /// </summary>
    public struct ValueInfoEntry
    {
        public string Value { get; set; }
        public string TypeName { get; set; }
        public TimeSpan? ExpireTime { get; set; }
        public ExpireType? ExpireType { get; set; }
    }

    /// <summary>
    /// 过期类型
    /// </summary>
    public enum ExpireType
    {
        /// <summary>
        /// 绝对过期
        /// 注:即自创建一段时间后就过期
        /// </summary>
        Absolute,

        /// <summary>
        /// 相对过期
        /// 注:即该键未被访问后一段时间后过期,若此键一直被访问则过期时间自动延长
        /// </summary>
        Relative,
    }

    #endregion

RedisCache.cs

/// <summary>
    /// Redis缓存
    /// </summary>
    public class RedisCache : ICache
    {
        /// <summary>
        /// 构造函数
        /// 注意:请以单例使用
        /// </summary>
        /// <param name="config">配置字符串</param>
        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<ValueInfoEntry>();
            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<T>(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

/// <summary>
    /// 系统缓存帮助类
    /// </summary>
    public class SystemCache : ICache
    {
        public object GetCache(string key)
        {
            return HttpRuntime.Cache[key];
        }

        public T GetCache<T>(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)

结语

这里提供了helper类,主要是为了封装缓存,使用起来更加方便。具体可以在其基础上进行扩展。

您可能感兴趣的文章:

相关文章