c# 实现redis读写

最近做一个C#项目,需要对radis进行读写。

 

首先引入System.Configuration,如下

实现代码如下:

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
public class ManualSuggestRedisHelper
    {
        private static IRedisClient GetManualSuggestClient()
        {
            var config = ConfigurationManager.ConnectionStrings["REDIS_MANUAL_VIDEO_LIST"].ConnectionString.Split(':');
            if (config.Length == 3)
            {
                int dbNum = int.Parse(config[2]);
                return new RedisClient(config[0], int.Parse(config[1]), db: dbNum);
            }
            else
            {
                return new RedisClient("192.168.86.15", 6379, db: 8);
            }
        }
 
        public static void AddRangeToList(string key, JSONObject value)
        {
            try
            {
                using (var redis = GetManualSuggestClient())
                {
                    redis.SetEntry(key, value.ToString());
                }
            }
            catch (Exception ex)
            {
                TxtLogger.DumpException(ex);
            }
        }
 
        public static void AddRangeToSuggestList(string key, List<string> value)
        {
            try
            {
                using (var redis = GetManualSuggestClient())
                {
                    redis.AddRangeToList(key, value);
                }
            }
            catch (Exception ex)
            {
                TxtLogger.DumpException(ex);
            }
        }
 
        public static void Remove(string key)
        {
            try
            {
                using (var redis = GetManualSuggestClient())
                {
                    redis.Remove(key);
                }
            }
            catch (Exception ex)
            {
                TxtLogger.AppendStringToTextFile("删除redis key存在异常——" + ex);
            }
        }
 
        public static bool ExistsRedis(string key)
        {
            try
            {
                using (var redis = GetManualSuggestClient())
                {
                    List<string> isExists = redis.GetAllItemsFromList(key);
                    if (isExists != null && isExists.Count() > 0)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                TxtLogger.DumpException(ex);
            }
            return false;
        }
 
    }

 

posted @   chanjuan  阅读(862)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示