**
第一步:nuget包——ServiceStack.Redis
**
public RedisCache _iCache = new RedisCache();
public void test(){
string tokenKey = "";
Token authToken = _iCache.Get<Token>(tokenKey);
if (authToken == null)
{
authToken = new Token();
authToken.SignToken = Guid.NewGuid().ToString().Replace("-", "");//设置token
authToken.ExpireTime = DateTime.Now.AddDays(1);//过期时间值
_iCache.Insert(tokenKey, authToken, authToken.ExpireTime);
}
}
/// <summary>
/// StackExchange Redis操作
/// </summary>
public class RedisCache
{
int Default_Timeout = 600;//默认超时时间(单位秒)
string address;
JsonSerializerSettings jsonConfig = new JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore };
ConnectionMultiplexer connectionMultiplexer;
IDatabase database;
class CacheObject<T>
{
public int ExpireTime { get; set; }
public bool ForceOutofDate { get; set; }
public T Value { get; set; }
}
public RedisCache()
{
this.address = "==============连接地址===================";
if (this.address == null || string.IsNullOrWhiteSpace(this.address.ToString()))
throw new ApplicationException("配置文件中未找到RedisServer的有效配置");
try
{
connectionMultiplexer = ConnectionMultiplexer.Connect(address);
//RedisDBId
int dbID = 0;
database = connectionMultiplexer.GetDatabase(dbID);
}
catch (Exception)
{
throw new ApplicationException("连接异常");
}
}
public RedisCache(string dbAddress, int dbID)
{
this.address = dbAddress;
if (this.address == null || string.IsNullOrWhiteSpace(this.address.ToString()))
throw new ApplicationException("Redis地址异常");
connectionMultiplexer = ConnectionMultiplexer.Connect(address);
database = connectionMultiplexer.GetDatabase(dbID);
}
/// <summary>
/// 连接超时设置
/// </summary>
public int TimeOut
{
get
{
return Default_Timeout;
}
set
{
Default_Timeout = value;
}
}
public object Get(string key)
{
return Get<object>(key);
}
public T Get<T>(string key)
{
DateTime begin = DateTime.Now;
var cacheValue = database.StringGet(key);
DateTime endCache = DateTime.Now;
var value = default(T);
if (!cacheValue.IsNullOrEmpty)
{
value = JsonConvert.DeserializeObject<T>(cacheValue, jsonConfig);
}
// DateTime endJson = DateTime.Now;
return value;
}
/// <summary>
/// 插入Redis,永不过期
/// </summary>
/// <param name="key"></param>
/// <param name="data"></param>
public void Insert(string key, object data)
{
// var jsonData = GetJsonData(data, TimeOut, false);
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData);
}
public void Insert(string key, object data, int cacheTime)
{
var timeSpan = TimeSpan.FromSeconds(cacheTime);
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData, timeSpan);
}
public void Insert(string key, object data, DateTime cacheTime)
{
var timeSpan = cacheTime - DateTime.Now;
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData, timeSpan);
}
public void Insert<T>(string key, T data)
{
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData);
}
public void Insert<T>(string key, T data, int cacheTime)
{
var timeSpan = TimeSpan.FromSeconds(cacheTime);
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData, timeSpan);
}
public void Insert<T>(string key, T data, DateTime cacheTime)
{
var timeSpan = cacheTime - DateTime.Now;
var jsonData = JsonConvert.SerializeObject(data);
database.StringSet(key, jsonData, timeSpan);
}
string GetJsonData(object data, int cacheTime, bool forceOutOfDate)
{
var cacheObject = new CacheObject<object>() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
}
string GetJsonData<T>(T data, int cacheTime, bool forceOutOfDate)
{
var cacheObject = new CacheObject<T>() { Value = data, ExpireTime = cacheTime, ForceOutofDate = forceOutOfDate };
return JsonConvert.SerializeObject(cacheObject, jsonConfig);//序列化对象
}
/// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
public void Remove(string key)
{
database.KeyDelete(key, CommandFlags.HighPriority);
}
/// <summary>
/// 判断key是否存在
/// </summary>
public bool Exists(string key)
{
if (!string.IsNullOrEmpty(key))
{
return database.KeyExists(key);
}
else
{
return false;
}
}
public void HashSet<T>(string key, string field, List<T> data)
{
if (data == null || data.Count < 1) return;
var jsonData = JsonConvert.SerializeObject(data);
HashEntry[] items = new HashEntry[data.Count];
for (int i = 0; i < data.Count; i++)
{
var item = data[i];
database.HashSet(key, field + "-" + i.ToString(), JsonConvert.SerializeObject(item));
}
}
public void ListSet<T>(string key, List<T> data)
{
if (data == null || data.Count < 1) return;
var jsonData = JsonConvert.SerializeObject(data);
HashEntry[] items = new HashEntry[data.Count];
for (int i = 0; i < data.Count; i++)
{
var item = data[i];
database.ListLeftPush(key, JsonConvert.SerializeObject(item));
}
}
public void ListLeftPush<T>(string key, List<T> data)
{
if (data == null || data.Count < 1) return;
HashEntry[] items = new HashEntry[data.Count];
for (int i = 0; i < data.Count; i++)
{
var item = data[i];
database.ListLeftPush(key, JsonConvert.SerializeObject(item));
}
}
/// <summary>
/// 向List中添加数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="data"></param>
/// <param name="mode">1:left 2right</param>
public void ListPush<T>(string key, T data, int mode = 1)
{
var jsonData = JsonConvert.SerializeObject(data);
if (mode == 1)
{
database.ListLeftPush(key, jsonData);
}
else
{
database.ListRightPush(key, jsonData);
}
}
public long ListDelete(string key, string value)
{
return database.ListRemove(key, value);
}
/// <summary>
/// 从List取出数据并从List中移除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="mode">1:right left</param>
/// <returns></returns>
public T ListPop<T>(string key, int mode = 1)
{
DateTime begin = DateTime.Now;
RedisValue cacheValue = RedisValue.Null;
if (mode == 1)
{
cacheValue = database.ListRightPop(key);
}
else
{
cacheValue = database.ListLeftPop(key);
}
// DateTime endCache = DateTime.Now;
var value = default(T);
if (!cacheValue.IsNullOrEmpty)
{
value = JsonConvert.DeserializeObject<T>(cacheValue, jsonConfig);
}
return value;
}
public List<T> ListGet<T>(string key)
{
DateTime begin = DateTime.Now;
var cacheValue = database.ListRange(key);
//DateTime endCache = DateTime.Now;
var list = new List<T>();
if (cacheValue != null)
{
foreach (var item in cacheValue)
{
list.Add(JsonConvert.DeserializeObject<T>(item, jsonConfig));
}
}
return list;
}
public List<T> ListGet<T>(string key, int start, int end)
{
DateTime begin = DateTime.Now;
var cacheValue = database.ListRange(key, start, end);
var list = new List<T>();
if (cacheValue != null)
{
foreach (var item in cacheValue)
{
list.Add(JsonConvert.DeserializeObject<T>(item, jsonConfig));
}
}
return list;
}
public long ListLength(string key)
{
return database.ListLength(key);
}
public bool HashDelete(string key, string field)
{
return database.HashDelete(key, field);
}
public T HashGet<T>(string key, string field)
{
DateTime begin = DateTime.Now;
var cacheValue = database.HashGet(key, field);
//DateTime endCache = DateTime.Now;
var value = default(T);
if (!cacheValue.IsNullOrEmpty)
{
value = JsonConvert.DeserializeObject<T>(cacheValue, jsonConfig);
}
return value;
}
public ISubscriber Subscriber
{
get
{
if (connectionMultiplexer != null)
{
return connectionMultiplexer.GetSubscriber();
}
else
{
return null;
}
}
}
public long Increment(string key, long step = 1)
{
var val = database.StringGet(key);
long id = Convert.ToInt64(val);
var trans = database.CreateTransaction();
trans.AddCondition(Condition.StringEqual(key, val));
trans.StringIncrementAsync(key, step);
if (trans.Execute())
{
return id + step;
}
else
{
return -1;
}
}
/// <summary>
/// 资源释放
/// </summary>
public void Release()
{
connectionMultiplexer.Dispose();
}
public List<string> GetAllKeys(string key)
{
var result = (string[])database.ScriptEvaluate(LuaScript.Prepare("return redis.call('KEYS',@keypattern)"), new { keypattern = key });
return result.ToList();
}
public bool DeleteKeys(List<string> keys)
{
bool flag = false;
if (keys != null && keys.Count > 0)
{
var res = database.KeyDelete(ConvertRedisKeys(keys));
if (res > 0) flag = true;
}
return flag;
}
private RedisKey[] ConvertRedisKeys(List<string> val)
{
return val.Select(k => (RedisKey)k).ToArray();
}
private RedisValue[] ConvertRedisValues(List<string> val)
{
return val.Select(k => (RedisValue)(JsonConvert.SerializeObject(k))).ToArray();
}
public void ListSetByPipeline(string key, List<string> codeList)
{
var val = ConvertRedisValues(codeList);
var res = database.ListLeftPush(key, val);
}
}