using Newtonsoft.Json; using ServiceStack.Redis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CarLocalMeter { public class RedisCache : ICache { public T GetCache(string key) { using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) { T value = default(T); var redisValue = client.Get(key); if (string.IsNullOrWhiteSpace(redisValue)) return value; ValueInfoEntry valueEntry = JsonConvert.DeserializeObject(redisValue.Trim()); value = JsonConvert.DeserializeObject(valueEntry.Value); if (valueEntry.ExpireTime > 0 && valueEntry.ExpireType == ExpireType.Relative) SetKeyExpire(key, valueEntry.ExpireTime); return value; } } public void RemoveCache(string key) { using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) { client.Del(key); } } public void SetCache(string key, object value, int timeout = 0, ExpireType expireType = ExpireType.Absolute) { string jsonStr = string.Empty; if (value is string) jsonStr = value as string; else jsonStr = JsonConvert.SerializeObject(value); ValueInfoEntry entry = new ValueInfoEntry { Value = jsonStr, TypeName = value.GetType().AssemblyQualifiedName, ExpireTime = timeout, ExpireType = expireType }; string theValue = JsonConvert.SerializeObject(entry); ; using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) { client.Set(key, theValue); if (timeout > 0) client.Expire(key, timeout); } } public void SetKeyExpire(string key, int expire) { using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) { client.Expire(key, expire); } } public void setRedisHash(string hashId, string key, object value, int timeout = 0, ExpireType expireType = ExpireType.Absolute) { string jsonStr = string.Empty; if (value is string) jsonStr = value as string; else jsonStr = JsonConvert.SerializeObject(value); ValueInfoEntry entry = new ValueInfoEntry { Value = jsonStr, TypeName = value.GetType().AssemblyQualifiedName, ExpireTime = timeout, ExpireType = expireType }; string theValue = JsonConvert.SerializeObject(entry); ; using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) { client.SetEntryInHash(hashId, key, theValue); if (timeout > 0) client.Expire(hashId, timeout); } } public Dictionary getRedisHash(string hashId) { using (RedisClient client = new RedisClient(AppConfigCache.redisIp, AppConfigCache.redisPort)) //还可以接密码跟长度,这里没设置 { if (client == null) return null; return client.GetAllEntriesFromHash(hashId); } } } }