本文章向大家介绍关于StackExchange.redis的一些总结,算是综合一个网上资料与自己的总结写的一个JOSN转换类,有一定的参考价值,需要的朋友可以参考一下。
private IDatabase cache;
private ConnectionMultiplexer connection;
构造
/// <summary>
/// 构造
/// </summary>
public RedisCacheImp()
{
connection = ConnectionMultiplexer.Connect(SystemConfig.RedisConnectionString);//这个是Redis连接
cache = connection.GetDatabase();
}
public RedisCacheImp(string connectionString)
{
connection = ConnectionMultiplexer.Connect(connectionString);//这个是Redis连接
cache = connection.GetDatabase();
}
//判断键值是否存在
public bool IsExist(string key)
{
return cache.KeyExists(key);
}
/// <summary>
/// 设置键值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expireTime"></param>
/// <returns></returns>
public bool SetCache<T>(string key, T value, DateTime? expireTime = null)
{
try
{
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string strValue = JsonConvert.SerializeObject(value, jsonOption);
if (string.IsNullOrEmpty(strValue))
{
return false;
}
if (expireTime == null)
{
return cache.StringSet(key, strValue);
}
else
{
return cache.StringSet(key, strValue, (expireTime.Value - DateTime.Now));
}
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return false;
}
/// <summary>
/// 异步的方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expireTime"></param>
/// <returns></returns>
public async Task<bool> SetCacheAsync<T>(string key, T value, DateTime? expireTime = null)
{
try
{
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
string strValue = JsonConvert.SerializeObject(value, jsonOption);
if (string.IsNullOrEmpty(strValue))
{
return false;
}
if (expireTime == null)
{
return awAIt cache.StringSetAsync(key, strValue);
}
else
{
return await cache.StringSetAsync(key, strValue, (expireTime.Value - DateTime.Now));
}
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return false;
}
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool RemoveCache(string key)
{
return cache.KeyDelete(key);
}
/// <summary>
/// 取得Cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T GetCache<T>(string key)
{
var t = default(T);
try
{
var value = cache.StringGet(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return t;
}
/// <summary>
/// 异步取得信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> GetCacheAsync<T>(string key)
{
var t = default(T);
try
{
var value = await cache.StringGetAsync(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = JsonConvert.DeserializeObject<T>(value);
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return t;
}
/// <summary>
/// 取得List缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> GetCaches<T>(string key)
{
var t = default(List<T>);
try
{
var value = cache.StringGet(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = (List<T>)JsonConvert.DeserializeObject<List<T>>(value);
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return t;
}
/// <summary>
/// 异步返回List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> GetCachesAsync<T>(string key)
{
var t = default(List<T>);
try
{
var value =await cache.StringGetAsync(key);
if (string.IsNullOrEmpty(value))
{
return t;
}
t = (List<T>)JsonConvert.DeserializeObject<List<T>>(value);
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
return t;
}
public int SetHashFieldCache<T>(string key, string fieldKey, T fieldValue)
{
return SetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, fieldValue } });
}
/// <summary>
// Dictionary<string, User> dic = new Dictionary<string, User>();
/// dic.Add("1", new User() { age = 99, name = "A01" });
/// dic.Add("2", new User() { age = 99, name = "A02" });
/// redis.SetHashFieldCache("users", dic);
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dict"></param>
/// <returns></returns>
public int SetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
int count = 0;
var jsonOption = new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
foreach (string fieldKey in dict.Keys)
{
string fieldValue = JsonConvert.SerializeObject(dict[fieldKey], jsonOption);
count += cache.HashSet(key, fieldKey, fieldValue) ? 1 : 0;
}
return count;
}
/// <summary>
/// var d = redis.GetHashFieldCache<User>("users", "1");
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="fieldKey"></param>
/// <returns></returns>
public T GetHashFieldCache<T>(string key, string fieldKey)
{
var dict = GetHashFieldCache<T>(key, new Dictionary<string, T> { { fieldKey, default(T) } });
return dict[fieldKey];
}
public Dictionary<string, T> GetHashFieldCache<T>(string key, Dictionary<string, T> dict)
{
foreach (string fieldKey in dict.Keys)
{
string fieldValue = cache.HashGet(key, fieldKey);
dict[fieldKey] = JsonConvert.DeserializeObject<T>(fieldValue);
}
return dict;
}
public Dictionary<string, T> GetHashCache<T>(string key)
{
Dictionary<string, T> dict = new Dictionary<string, T>();
var hashFields = cache.HashGetAll(key);
foreach (HashEntry field in hashFields)
{
dict[field.Name] = JsonConvert.DeserializeObject<T>(field.Value);
}
return dict;
}
/// <summary>
/// 将Hash转换成List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> GetHashToListCache<T>(string key)
{
List<T> list = new List<T>();
var hashFields = cache.HashGetAll(key);
foreach (HashEntry field in hashFields)
{
list.Add(JsonConvert.DeserializeObject<T>(field.Value));
}
return list;
}
/// <summary>
/// redis.RemoveHashFieldCache("users", "1");
/// </summary>
/// <param name="key"></param>
/// <param name="fieldKey"></param>
/// <returns></returns>
public bool RemoveHashFieldCache(string key, string fieldKey)
{
Dictionary<string, bool> dict = new Dictionary<string, bool> { { fieldKey, false } };
dict = RemoveHashFieldCache(key, dict);
return dict[fieldKey];
}
public Dictionary<string, bool> RemoveHashFieldCache(string key, Dictionary<string, bool> dict)
{
foreach (string fieldKey in dict.Keys)
{
dict[fieldKey] = cache.HashDelete(key, fieldKey);
}
return dict;
}
/// <summary>
/// 释放
/// </summary>
public void Dispose()
{
if (connection != null)
{
connection.Close();
}
GC.SuppressFinalize(this);
}