1 public class RedisHelper 2 { 3 /// <summary> 4 /// 默认的 Key 值(用来当作 RedisKey 的前缀) 5 /// </summary> 6 private static readonly string DefaultKey = "G_"; 7 /// <summary> 8 /// 连接字符串 9 /// </summary> 10 private static readonly string ConnectionString = "127.0.0.1:6379"; 11 /// <summary> 12 /// 锁 13 /// </summary> 14 private readonly object _lock = new object(); 15 /// <summary> 16 /// 连接对象 17 /// </summary> 18 private volatile IConnectionMultiplexer _connection; 19 /// <summary> 20 /// 数据库 21 /// </summary> 22 private IDatabase _db; 23 public RedisHelper() 24 { 25 _connection = ConnectionMultiplexer.Connect(ConnectionString); 26 _db = GetDatabase(); 27 } 28 /// <summary> 29 /// 获取连接 30 /// </summary> 31 /// <returns></returns> 32 protected IConnectionMultiplexer GetConnection() 33 { 34 if (_connection != null && _connection.IsConnected) 35 { 36 return _connection; 37 } 38 lock (_lock) 39 { 40 if (_connection != null && _connection.IsConnected) 41 { 42 return _connection; 43 } 44 45 if (_connection != null) 46 { 47 _connection.Dispose(); 48 } 49 _connection = ConnectionMultiplexer.Connect(ConnectionString); 50 } 51 52 return _connection; 53 } 54 /// <summary> 55 /// 获取数据库 56 /// </summary> 57 /// <param name="db"></param> 58 /// <returns></returns> 59 public IDatabase GetDatabase(int? db = null) 60 { 61 return GetConnection().GetDatabase(db ?? -1); 62 } 63 64 65 #region 字符串 66 67 68 /// <summary> 69 /// 获取字符串 70 /// </summary> 71 /// <param name="redisKey"></param> 72 /// <param name="expiry"></param> 73 /// <returns></returns> 74 public string StringGet(string redisKey, TimeSpan? expiry = null) 75 { 76 return _db.StringGet(redisKey); 77 } 78 /// <summary> 79 /// 设置 key 并保存字符串(如果 key 已存在,则覆盖值) 80 /// </summary> 81 /// <param name="redisKey"></param> 82 /// <param name="redisValue"></param> 83 /// <param name="expiry"></param> 84 /// <returns></returns> 85 public bool StringSet(string redisKey, string redisValue, TimeSpan? expiry = null) 86 { 87 return _db.StringSet(redisKey, redisValue, expiry); 88 } 89 /// <summary> 90 /// 保存多个 Key-value 91 /// </summary> 92 /// <param name="keyValuePairs"></param> 93 /// <returns></returns> 94 public bool StringSet(IEnumerable<KeyValuePair<RedisKey, RedisValue>> keyValuePairs) 95 { 96 keyValuePairs = keyValuePairs.Select(x => new KeyValuePair<RedisKey, RedisValue>(x.Key, x.Value)); 97 return _db.StringSet(keyValuePairs.ToArray()); 98 } 99 100 /// <summary> 101 /// 存储一个对象(该对象会被序列化保存) 102 /// </summary> 103 /// <param name="redisKey"></param> 104 /// <param name="redisValue"></param> 105 /// <param name="expiry"></param> 106 /// <returns></returns> 107 public bool StringSet<T>(string redisKey, T redisValue, TimeSpan? expiry = null) 108 { 109 var json = Serialize(redisValue); 110 return _db.StringSet(redisKey, json, expiry); 111 } 112 113 /// <summary> 114 /// 获取一个对象(会进行反序列化) 115 /// </summary> 116 /// <param name="redisKey"></param> 117 /// <param name="expiry"></param> 118 /// <returns></returns> 119 public T StringGet<T>(string redisKey, TimeSpan? expiry = null) 120 { 121 return Deserialize<T>(_db.StringGet(redisKey)); 122 } 123 124 #endregion 125 #region hash 126 /// <summary> 127 /// 判断该字段是否存在 hash 中 128 /// </summary> 129 /// <param name="redisKey"></param> 130 /// <param name="hashField"></param> 131 /// <returns></returns> 132 public bool HashExists(string redisKey, string hashField) 133 { 134 return _db.HashExists(redisKey, hashField); 135 } 136 137 /// <summary> 138 /// 从 hash 中移除指定字段 139 /// </summary> 140 /// <param name="redisKey"></param> 141 /// <param name="hashField"></param> 142 /// <returns></returns> 143 public bool HashDelete(string redisKey, string hashField) 144 { 145 return _db.HashDelete(redisKey, hashField); 146 } 147 148 /// <summary> 149 /// 从 hash 中移除指定字段 150 /// </summary> 151 /// <param name="redisKey"></param> 152 /// <param name="hashField"></param> 153 /// <returns></returns> 154 public long HashDelete(string redisKey, IEnumerable<RedisValue> hashField) 155 { 156 return _db.HashDelete(redisKey, hashField.ToArray()); 157 } 158 159 /// <summary> 160 /// 在 hash 设定值 161 /// </summary> 162 /// <param name="redisKey"></param> 163 /// <param name="hashField"></param> 164 /// <param name="value"></param> 165 /// <returns></returns> 166 public bool HashSet(string redisKey, string hashField, string value) 167 { 168 return _db.HashSet(redisKey, hashField, value); 169 } 170 171 /// <summary> 172 /// 在 hash 中设定值 173 /// </summary> 174 /// <param name="redisKey"></param> 175 /// <param name="hashFields"></param> 176 public void HashSet(string redisKey, IEnumerable<HashEntry> hashFields) 177 { 178 _db.HashSet(redisKey, hashFields.ToArray()); 179 } 180 181 /// <summary> 182 /// 在 hash 中获取值 183 /// </summary> 184 /// <param name="redisKey"></param> 185 /// <param name="hashField"></param> 186 /// <returns></returns> 187 public RedisValue HashGet(string redisKey, string hashField) 188 { 189 return _db.HashGet(redisKey, hashField); 190 } 191 192 /// <summary> 193 /// 在 hash 中获取值 194 /// </summary> 195 /// <param name="redisKey"></param> 196 /// <param name="hashField"></param> 197 /// <param name="value"></param> 198 /// <returns></returns> 199 public RedisValue[] HashGet(string redisKey, RedisValue[] hashField, string value) 200 { 201 return _db.HashGet(redisKey, hashField); 202 } 203 204 /// <summary> 205 /// 从 hash 返回所有的字段值 206 /// </summary> 207 /// <param name="redisKey"></param> 208 /// <returns></returns> 209 public IEnumerable<RedisValue> HashKeys(string redisKey) 210 { 211 return _db.HashKeys(redisKey); 212 } 213 214 /// <summary> 215 /// 返回 hash 中的所有值 216 /// </summary> 217 /// <param name="redisKey"></param> 218 /// <returns></returns> 219 public RedisValue[] HashValues(string redisKey) 220 { 221 return _db.HashValues(redisKey); 222 } 223 224 /// <summary> 225 /// 在 hash 设定值(序列化) 226 /// </summary> 227 /// <param name="redisKey"></param> 228 /// <param name="hashField"></param> 229 /// <param name="value"></param> 230 /// <returns></returns> 231 public bool HashSet<T>(string redisKey, string hashField, T value) 232 { 233 var json = Serialize(value); 234 ObjectSerializer serializer = new ObjectSerializer(); 235 byte[] array = serializer.Serialize(value); 236 return _db.HashSet(redisKey, hashField, array); 237 } 238 239 /// <summary> 240 /// 在 hash 中获取值(反序列化) 241 /// </summary> 242 /// <param name="redisKey"></param> 243 /// <param name="hashField"></param> 244 /// <returns></returns> 245 public T HashGet<T>(string redisKey, string hashField) 246 { 247 ObjectSerializer serializer = new ObjectSerializer(); 248 return (T)serializer.Deserialize(_db.HashGet(redisKey, hashField)); 249 250 251 252 // return Deserialize<T>(_db.HashGet(redisKey, hashField)); 253 } 254 255 #endregion 256 257 258 #region key 259 260 /// <summary> 261 /// 移除指定 Key 262 /// </summary> 263 /// <param name="redisKey"></param> 264 /// <returns></returns> 265 public bool KeyDelete(string redisKey) 266 { 267 return _db.KeyDelete(redisKey); 268 } 269 270 /// <summary> 271 /// 移除指定 Key 272 /// </summary> 273 /// <param name="redisKeys"></param> 274 /// <returns></returns> 275 public long KeyDelete(IEnumerable<string> redisKeys) 276 { 277 var keys = redisKeys.Select(x => (RedisKey)x); 278 return _db.KeyDelete(keys.ToArray()); 279 } 280 281 /// <summary> 282 /// 校验 Key 是否存在 283 /// </summary> 284 /// <param name="redisKey"></param> 285 /// <returns></returns> 286 public bool KeyExists(string redisKey) 287 { 288 return _db.KeyExists(redisKey); 289 } 290 291 /// <summary> 292 /// 重命名 Key 293 /// </summary> 294 /// <param name="redisKey"></param> 295 /// <param name="redisNewKey"></param> 296 /// <returns></returns> 297 public bool KeyRename(string redisKey, string redisNewKey) 298 { 299 return _db.KeyRename(redisKey, redisNewKey); 300 } 301 302 /// <summary> 303 /// 设置 Key 的时间 304 /// </summary> 305 /// <param name="redisKey"></param> 306 /// <param name="expiry"></param> 307 /// <returns></returns> 308 public bool KeyExpire(string redisKey, TimeSpan? expiry) 309 { 310 return _db.KeyExpire(redisKey, expiry); 311 } 312 #endregion 313 314 /// <summary> 315 /// 反序列化 316 /// </summary> 317 /// <typeparam name="T"></typeparam> 318 /// <param name="serializedObject"></param> 319 /// <returns></returns> 320 protected T Deserialize<T>(byte[] serializedObject) 321 { 322 if (serializedObject == null) 323 { 324 return default(T); 325 } 326 var json = Encoding.UTF8.GetString(serializedObject); 327 return JsonConvert.DeserializeObject<T>(json); 328 } 329 /// <summary> 330 /// 判断是否已经设置 331 /// </summary> 332 /// <param name="key"></param> 333 /// <returns></returns> 334 public bool IsExists(string key) 335 { 336 return _db.KeyExists(key); 337 } 338 /// <summary> 339 /// 序列化 340 /// </summary> 341 /// <param name="data"></param> 342 /// <returns>byte[]</returns> 343 private byte[] Serialize(object data) 344 { 345 var json = JsonConvert.SerializeObject(data); 346 return Encoding.UTF8.GetBytes(json); 347 } 348 349 350 351 352 }
二进制序列化,次方法不能通用解析,建议序列化为Json
1 public class ObjectSerializer 2 { 3 protected readonly System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 4 public virtual byte[] Serialize(object value) 5 { 6 byte[] result; 7 if (value == null) 8 { 9 result = null; 10 } 11 else 12 { 13 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); 14 memoryStream.Seek(0L, System.IO.SeekOrigin.Begin); 15 this.bf.Serialize(memoryStream, value); 16 result = memoryStream.ToArray(); 17 } 18 return result; 19 } 20 public virtual object Deserialize(byte[] someBytes) 21 { 22 object result; 23 if (someBytes == null) 24 { 25 result = null; 26 } 27 else 28 { 29 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); 30 memoryStream.Write(someBytes, 0, someBytes.Length); 31 memoryStream.Seek(0L, System.IO.SeekOrigin.Begin); 32 object obj = this.bf.Deserialize(memoryStream); 33 result = obj; 34 } 35 return result; 36 } 37 public string FromUtf8Bytes(byte[] bytes) 38 { 39 string result; 40 if (bytes != null) 41 { 42 result = System.Text.Encoding.UTF8.GetString(bytes, 0, bytes.Length); 43 } 44 else 45 { 46 result = null; 47 } 48 return result; 49 } 50 public byte[] ToUtf8Bytes(string value) 51 { 52 return System.Text.Encoding.UTF8.GetBytes(value); 53 } 54 public virtual byte[] JsonSerializer<T>(T t) 55 { 56 DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T)); 57 System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); 58 dataContractJsonSerializer.WriteObject(memoryStream, t); 59 return memoryStream.ToArray(); 60 } 61 public virtual T JsonDeserialize<T>(byte[] someBytes) 62 { 63 DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T)); 64 System.IO.MemoryStream stream = new System.IO.MemoryStream(someBytes); 65 return (T)((object)dataContractJsonSerializer.ReadObject(stream)); 66 } 67 }