page contents

详解C#中Helper类的使用

本文讲述了详解C#中Helper类的使用!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

attachments-2022-06-puClnUIn62b3d11aa8019.png

本文讲述了详解C#中Helper类的使用!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

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

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

使用方法
1.引用CSRedisCore

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

2.增加helper类代码

CacheHelper.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// <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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/// <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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/// <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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/// <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(
  • 发表于 2022-06-23 10:34
  • 阅读 ( 302 )
  • 分类:C/C++开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
轩辕小不懂
轩辕小不懂

2403 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. 小柒 1474 文章
  3. Pack 1135 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章