RedisHelper.cs
3.47 KB
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
110
111
112
113
114
115
116
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StackExchange.Redis;
namespace Quiz.SiteBase
{
public class RedisHelper
{
private readonly static string REDIS_CONN = "121.40.109.21:6379,password=123456";
private readonly static string REDIS_IP = "121.40.109.21";
private readonly static int REDIS_PORT = 6379;
private ConnectionMultiplexer redis = null;
private IDatabase database = null;
private IServer server = null;
private int mydb = 0;
public RedisHelper(int db)
{
mydb = db;
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(REDIS_CONN);
database = redis.GetDatabase(mydb);
server = redis.GetServer(REDIS_IP, REDIS_PORT);
redis.ErrorMessage += Redis_ErrorMessage;
}
}
/// <summary>
/// 异常记录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void Redis_ErrorMessage(object sender, RedisErrorEventArgs e)
{
//LogHelper.WriteLog("Redis", new Exception(e.Message));
}
/// <summary>
/// 通过key获取value
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string StringGet(string key)
{
return database.StringGet(key);
}
/// <summary>
/// 新增key value
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
/// <param name="exp"></param>
/// <returns></returns>
public bool StringSet(string key, string val, TimeSpan? exp = default(TimeSpan?))
{
return database.StringSet(key, val, exp);
}
/// <summary>
/// 新增key value
/// </summary>
/// <param name="key"></param>
/// <param name="val"></param>
/// <param name="exp"></param>
/// <returns></returns>
public bool ObjectSet(string key, object val, TimeSpan? exp = default(TimeSpan?))
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(val);
return database.StringSet(key, json, exp);
}
/// <summary>
/// 获取key
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public IEnumerable<RedisKey> LikeKeys(string pattern = "*")
{
return server.Keys(database: mydb, pattern: pattern);
}
/// <summary>
/// 查询
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
public Dictionary<string, string> GetLikeKeyValue(string pattern = "*")
{
IEnumerable<RedisKey> list = LikeKeys(pattern);
Dictionary<string, string> dic = new Dictionary<string, string>();
if (list != null && list.Count() > 0)
{
foreach (var item in list)
{
dic.Add(item, StringGet(item));
}
}
return dic;
}
/// <summary>
/// 删除key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool KeyDelete(string key)
{
return database.KeyDelete(key);
}
}
}