Redis编程:下载开发驱动: ServiceStack.Redis
注意:如果把开发驱动(ServiceStack.Redis)引用到自己项目中,运行项目报:ServiceStack.Common缺少依赖项,把Newtonsoft.Json.dll也引用到项目中。
redis.conf:requirepass 123456
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using ServiceStack.Redis;
using ServiceStack.Common;
using ServiceStack.ServiceInterface;
using ServiceStack.Text;
namespace Redis.DBUtility
{
public class RedisManager
{
//192.168.1.133:6379(无密码),[email protected]:6379(有密码)说明:@前面是密码,@后面IP和端口号; requirepass@Host:Port
private static string redisReadWriteHostsPath = ConfigurationManager.AppSettings["ReadWriteHostsPath"];
private static string redisReadOnlyHostsPath = ConfigurationManager.AppSettings["ReadOnlyHostsPath"];
protected static object _lock = new object();//锁住当前对象
private static PooledRedisClientManager prcm;
private static RedisManager instance;
public static RedisManager Instance()
{
if (instance == null)
instance = new RedisManager();
return instance;
}
///
/// 构造函数
///
public RedisManager()
{
lock (_lock)
{
if (prcm == null)
{
prcm = CreateManager(new string[] { redisReadWriteHostsPath }, new string[] { redisReadOnlyHostsPath });
prcm.ConnectTimeout =2*60*1000;//设置连接超时时间(单位:毫秒)
}
}
}
#region ---连接信息---
private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
{
//支持读写分离,均衡负载
return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
{
MaxWritePoolSize = 1024, // “写”链接池链接数
MaxReadPoolSize = 1024, // “读”链接池链接数
AutoStart = true,
});
}
#endregion
///
/// 获取Redis全部Key
///
///
public List GetAllKeys()
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.GetAllKeys();
}
}
catch (Exception ex)
{
return null;
}
}
public string GetRandomKey()
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.GetRandomKey();
}
}
catch (Exception ex)
{
return null;
}
}
public bool ContainsKey(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.ContainsKey(key);
}
}
catch (Exception ex)
{
return false;
}
}
public List SearchKeys(string pattern)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.SearchKeys(pattern);
}
}
catch (Exception ex)
{
return null;
}
}
public bool Remove(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Remove(key);
}
}
catch (Exception ex)
{
return false;
}
}
#region ---item---
///
/// 获取单体
///
///
///
///
public T Item_Get(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Get(key);
}
}
catch (Exception ex)
{
//log4记录错误日志
return default(T);
}
}
///
/// 设置单体
///
///
///
///
///
public bool Item_Set(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Set(key, value);
}
}
catch (Exception ex)
{
//log4记录错误日志
return false;
}
}
///
/// 设置单体
///
///
///
///
///
///
public bool Item_Set(string key, T value, TimeSpan timeSpan)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Set(key, value, timeSpan);
}
}
catch (Exception ex)
{
//log4记录错误日志
return false;
}
}
///
/// 移除单体
///
///
///
public bool Item_Remove(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Remove(key);
}
}
catch (Exception ex)
{
//log4记录错误日志
return false;
}
}
#endregion
#region ---List---
///
/// 将一个值插入到List的最前面
///
///
///
///
///
public bool List_AddPrepend(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
var redisTypedClient = redisClient.GetTypedClient();
redisTypedClient.PrependItemToList(redisTypedClient.Lists[key], value);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool List_Add(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
var redisTypedClient = redisClient.GetTypedClient();
redisTypedClient.AddItemToList(redisTypedClient.Lists[key], value);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool List_Remove(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
var redisTypedClient = redisClient.GetTypedClient();
return redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], value) > 0;
}
}
catch
{
return false;
}
}
public bool List_RemoveAll(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
var redisTypedClient = redisClient.GetTypedClient();
redisTypedClient.Lists[key].RemoveAll();
}
return true;
}
catch
{
return false;
}
}
public long List_Count(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.GetListCount(key);
}
}
catch
{
return 0;
}
}
///
/// 注意:获取key全部值再去Contains,数据量请慎用
///
///
///
///
///
public bool List_Contains(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.GetAllItemsFromList(key).Contains(jsonText);
}
}
catch
{
return false;
}
}
public List List_GetRange(string key, int start, int count)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var c = redisClient.GetTypedClient();
return c.Lists[key].GetRange(start, start + count - 1);
}
}
public List List_GetRange_Sort(string key, int start, int count)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var c = redisClient.GetTypedClient();
return c.Lists[key].GetRangeFromSortedList(start, start + count);
}
}
public List List_GetList(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var c = redisClient.GetTypedClient();
return c.Lists[key].GetRange(0, c.Lists[key].Count);
}
}
///
/// 分页
///
///
///
///
///
///
public List List_GetList(string key, int pageIndex, int pageSize)
{
int start = pageSize * (pageIndex - 1);
return List_GetRange(key, start, pageSize);
}
///
/// 设置缓存过期
///
///
///
public void List_SetExpire(string key, DateTime datetime)
{
using (IRedisClient redisClient = prcm.GetClient())
{
redisClient.ExpireEntryAt(key, datetime);
}
}
#endregion
#region ---Set---
public bool Set_Add(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
redisClient.AddItemToSet(key, jsonText);
}
return true;
}
catch (Exception ex)
{
//LogUtil.Error("Set_Add", ex);
return false;
}
}
///
/// 判断指定SetId的HashSet中是否包含指定的value(仅仅支持字符串)
///
///
///
///
///
public bool Set_Contains(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.SetContainsItem(key, jsonText);
}
}
catch (Exception ex)
{
//LogUtil.Error("Set_Contains", ex);
return false;
}
}
///
/// 移除单个Set
///
///
///
///
///
public bool Set_Remove(string key, T value)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
redisClient.RemoveItemFromSet(key, jsonText);
}
return true;
}
catch (Exception ex)
{
//LogUtil.Error("Set_Remove", ex);
return false;
}
}
public long Set_Count(string key)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.GetSetCount(key);
}
}
catch (Exception ex)
{
//LogUtil.Error("Set_Count", ex);
return 0;
}
}
///
/// 获取set并集
///
///
///
public HashSet Set_Union(params string[] keys)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
HashSet union = redisClient.GetUnionFromSets(keys);
return union;
}
}
catch (Exception ex)
{
//LogUtil.Error("Set_Union", ex);
return null;
}
}
///
/// 获取set交集
///
///
///
public HashSet Set_Intersect(params string[] keys)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
HashSet inter = redisClient.GetIntersectFromSets(keys);
return inter;
}
}
catch (Exception ex)
{
//LogUtil.Error("Set_Intersect", ex);
return null;
}
}
///
/// 获取set差集
///
///
///
///
public HashSet Set_Differences(string fromSet, params string[] toSet)
{
try
{
using (IRedisClient redisClient = prcm.GetClient())
{
HashSet diff = redisClient.GetDifferencesFromSet(fromSet, toSet);
return diff;
}
}
catch (Exception ex)
{
//LogUtil.Error("Set_Differences", ex);
return null;
}
}
#endregion
#region ---Hash---
///
/// 判断某个数据是否已经被缓存
///
///
///
///
///
public bool Hash_Exist(string key, string dataKey)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.HashContainsEntry(key, dataKey);
}
}
///
/// 存储数据到hash表
///
///
///
///
///
///
public bool Hash_Set(string key, string dataKey, T value)
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.SetEntryInHash(key, dataKey, jsonText);
}
}
///
/// 移除hash中的某值
///
///
///
///
///
public bool Hash_Remove(string key, string dataKey)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.RemoveEntryFromHash(key, dataKey);
}
}
///
/// 移除整个hash
///
///
///
///
public bool Hash_Remove(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.Remove(key);
}
}
///
/// 从hash表获取数据
///
///
///
///
///
public T Hash_Get(string key, string dataKey)
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = redisClient.GetValueFromHash(key, dataKey);
return ServiceStack.Text.JsonSerializer.DeserializeFromString(jsonText);
}
}
///
/// 获取整个hash的数据
///
///
///
///
public List Hash_GetAll(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var list = redisClient.GetHashValues(key);
if (list != null && list.Count > 0)
{
List result = new List();
foreach (var item in list)
{
var jsonText = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
result.Add(jsonText);
}
return result;
}
return null;
}
}
///
/// 设置缓存过期
///
///
///
public bool Hash_SetExpire(string key, DateTime dateTime)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.ExpireEntryAt(key, dateTime);
}
}
#endregion
#region ---SortedSet---
//SortedSet注意:对象的保存是以score asc排序的
///
/// 添加数据到 SortedSet
///
///
///
///
///
public bool SortedSet_Add(string key, T value, double score)
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.AddItemToSortedSet(key, jsonText, score);
}
}
///
/// 移除数据从SortedSet
///
///
///
///
///
public bool SortedSet_Remove(string key, T value)
{
using (IRedisClient redisClient = prcm.GetClient())
{
string jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.RemoveItemFromSortedSet(key, jsonText);
}
}
public long SortedSet_Remove(string key, double fromScore, double toScore)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.RemoveRangeFromSortedSetByScore(key, fromScore, toScore);
}
}
///
/// 修剪SortedSet
///
///
/// 保留的条数
///
public long SortedSet_Trim(string key, int minRank, int maxRank = 9999999)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.RemoveRangeFromSortedSet(key, minRank, maxRank);
}
}
///
/// 获取SortedSet的长度
///
///
///
public long SortedSet_Count(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.GetSortedSetCount(key);
}
}
///
/// 获取SortedSet的分页数据
///
///
///
///
///
///
public List SortedSet_GetList(string key, int pageIndex, int pageSize)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var list = redisClient.GetRangeFromSortedSetDesc(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);
if (list != null && list.Count > 0)
{
List result = new List();
foreach (var item in list)
{
var jsonText = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
result.Add(jsonText);
}
return result;
}
}
return null;
}
///
/// 获取SortedSet的全部数据
///
///
///
///
///
///
public List SortedSet_GetListALL(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var list = redisClient.GetRangeFromSortedSet(key, 0, 9999999);
if (list != null && list.Count > 0)
{
List result = new List();
foreach (var item in list)
{
var jsonText = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
result.Add(jsonText);
}
return result;
}
}
return null;
}
///
/// 获取SortedSet的第一条数据
///
///
///
///
///
///
public T SortedSet_GetFirstData(string key)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var list = redisClient.GetRangeFromSortedSet(key, 0, 0);
if (list != null && list.Count > 0)
{
List result = new List();
foreach (var item in list)
{
var jsonText = ServiceStack.Text.JsonSerializer.DeserializeFromString(item);
result.Add(jsonText);
}
return result[0];
}
}
return default(T);
}
///
/// 设置缓存过期
///
///
///
public bool SortedSet_SetExpire(string key, DateTime dateTime)
{
using (IRedisClient redisClient = prcm.GetClient())
{
return redisClient.ExpireEntryAt(key, dateTime);
}
}
///
/// 获取SortedSet中数据的分数
///
///
///
///
///
public double SortedSet_GetItemScore(string key, T value)
{
using (IRedisClient redisClient = prcm.GetClient())
{
var jsonText = ServiceStack.Text.JsonSerializer.SerializeToString(value);
return redisClient.GetItemScoreInSortedSet(key, jsonText);
}
}
#endregion
}
}
调用:
RedisManager.Instance().Item_Set(string.Format("redis_user_id_{0}", 1), "杨飞宰");