首先nuget:
- ServiceStack.Redis
- ServiceStack.Common
- ServiceStack.interfaces
- ServiceStack.Text
基本版
public sealed class RedisConfigInfo
{
public string WriteServerList = "127.0.0.1:6379";
public string ReadServerList = "127.0.0.1:6379";
public int MaxWritePoolSize = 60;
public int MaxReadPoolSize = 60;
public int LocalCacheTime = 180;
public bool AutoStart = true;
public bool RecordeLog = false;
}
public class RedisManager
{
private static RedisConfigInfo RedisConfigInfo = new RedisConfigInfo();
private static PooledRedisClientManager prcManager;
static RedisManager()
{
CreateManager();
}
private static void CreateManager()
{
string[] WriteServerConStr = RedisConfigInfo.WriteServerList.Split(',');
string[] ReadServerConStr = RedisConfigInfo.ReadServerList.Split(',');
prcManager = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr,
new RedisClientManagerConfig
{
MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize,
MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize,
AutoStart = RedisConfigInfo.AutoStart,
});
}
public static IRedisClient GetClient()
{
return prcManager.GetClient();
}
}
public abstract class RedisBase : IDisposable
{
public IRedisClient iClient { get; private set; }
public RedisBase()
{
iClient = RedisManager.GetClient();
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
iClient.Dispose();
iClient = null;
}
}
this._disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Transcation()
{
using (IRedisTransaction irt = this.iClient.CreateTransaction())
{
try
{
irt.QueueCommand(r => r.Set("key", 20));
irt.QueueCommand(r => r.Increment("key", 1));
irt.Commit();
}
catch (Exception ex)
{
irt.Rollback();
throw ex;
}
}
}
public virtual void FlushAll()
{
iClient.FlushAll();
}
public void Save()
{
iClient.Save();
}
public void SaveAsync()
{
iClient.SaveAsync();
}
}
服务层:五大数据结构
public class RedisHashService : RedisBase
{
#region 添加
public bool SetEntryInHash(string hashid, string key, string value)
{
return base.iClient.SetEntryInHash(hashid, key, value);
}
public bool SetEntryInHashIfNotExists(string hashid, string key, string value)
{
return base.iClient.SetEntryInHashIfNotExists(hashid, key, value);
}
public void StoreAsHash<T>(T t)
{
base.iClient.StoreAsHash<T>(t);
}
#endregion
#region 获取
public T GetFromHash<T>(object id)
{
return base.iClient.GetFromHash<T>(id);
}
public Dictionary<string, string> GetAllEntriesFromHash(string hashid)
{
return base.iClient.GetAllEntriesFromHash(hashid);
}
public long GetHashCount(string hashid)
{
return base.iClient.GetHashCount(hashid);
}
public List<string> GetHashKeys(string hashid)
{
return base.iClient.GetHashKeys(hashid);
}
public List<string> GetHashValues(string hashid)
{
return base.iClient.GetHashValues(hashid);
}
public string GetValueFromHash(string hashid, string key)
{
return base.iClient.GetValueFromHash(hashid, key);
}
public List<string> GetValuesFromHash(string hashid, string[] keys)
{
return base.iClient.GetValuesFromHash(hashid, keys);
}
#endregion
#region 删除
public bool RemoveEntryFromHash(string hashid, string key)
{
return base.iClient.RemoveEntryFromHash(hashid, key);
}
#endregion
#region 其它
public bool HashContainsEntry(string hashid, string key)
{
return base.iClient.HashContainsEntry(hashid, key);
}
public double IncrementValueInHash(string hashid, string key, double countBy)
{
return base.iClient.IncrementValueInHash(hashid, key, countBy);
}
#endregion
}
public class RedisListService : RedisBase
{
#region 赋值
public void LPush(string key, string value)
{
base.iClient.PushItemToList(key, value);
}
public void LPush(string key, string value, DateTime dt)
{
base.iClient.PushItemToList(key, value);
base.iClient.ExpireEntryAt(key, dt);
}
public void LPush(string key, string value, TimeSpan sp)
{
base.iClient.PushItemToList(key, value);
base.iClient.ExpireEntryIn(key, sp);
}
public void RPush(string key, string value)
{
base.iClient.PrependItemToList(key, value);
}
public void RPush(string key, string value, DateTime dt)
{
base.iClient.PrependItemToList(key, value);
base.iClient.ExpireEntryAt(key, dt);
}
public void RPush(string key, string value, TimeSpan sp)
{
base.iClient.PrependItemToList(key, value);
base.iClient.ExpireEntryIn(key, sp);
}
public void Add(string key, string value)
{
base.iClient.AddItemToList(key, value);
}
public void Add(string key, string value, DateTime dt)
{
base.iClient.AddItemToList(key, value);
base.iClient.ExpireEntryAt(key, dt);
}
public void Add(string key, string value, TimeSpan sp)
{
base.iClient.AddItemToList(key, value);
base.iClient.ExpireEntryIn(key, sp);
}
public void Add(string key, List<string> values)
{
base.iClient.AddRangeToList(key, values);
}
public void Add(string key, List<string> values, DateTime dt)
{
base.iClient.AddRangeToList(key, values);
base.iClient.ExpireEntryAt(key, dt);
}
public void Add(string key, List<string> values, TimeSpan sp)
{
base.iClient.AddRangeToList(key, values);
base.iClient.ExpireEntryIn(key, sp);
}
#endregion
#region 获取值
public long Count(string key)
{
return base.iClient.GetListCount(key);
}
public List<string> Get(string key)
{
return base.iClient.GetAllItemsFromList(key);
}
public List<string> Get(string key, int star, int end)
{
return base.iClient.GetRangeFromList(key, star, end);
}
#endregion
#region 阻塞命令
public string BlockingPopItemFromList(string key, TimeSpan? sp)
{
return base.iClient.BlockingPopItemFromList(key, sp);
}
public ItemRef BlockingPopItemFromLists(string[] keys, TimeSpan? sp)
{
return base.iClient.BlockingPopItemFromLists(keys, sp);
}
public string BlockingDequeueItemFromList(string key, TimeSpan? sp)
{
return base.iClient.BlockingDequeueItemFromList(key, sp);
}
public ItemRef BlockingDequeueItemFromLists(string[] keys, TimeSpan? sp)
{
return base.iClient.BlockingDequeueItemFromLists(keys, sp);
}
public string BlockingPopAndPushItemBetweenLists(string fromkey, string tokey, TimeSpan? sp)
{
return base.iClient.BlockingPopAndPushItemBetweenLists(fromkey, tokey, sp);
}
#endregion
#region 删除
public string PopItemFromList(string key)
{
var sa = base.iClient.CreateSubscription();
return base.iClient.PopItemFromList(key);
}
public string DequeueItemFromList(string key)
{
return base.iClient.DequeueItemFromList(key);
}
public long RemoveItemFromList(string key, string value)
{
return base.iClient.RemoveItemFromList(key, value);
}
public string RemoveEndFromList(string key)
{
return base.iClient.RemoveEndFromList(key);
}
public string RemoveStartFromList(string key)
{
return base.iClient.RemoveStartFromList(key);
}
#endregion
#region 其它
public string PopAndPushItemBetweenLists(string fromKey, string toKey)
{
return base.iClient.PopAndPushItemBetweenLists(fromKey, toKey);
}
#endregion
#region 发布订阅
public void Publish(string channel, string message)
{
base.iClient.PublishMessage(channel, message);
}
public void Subscribe(string channel, Action<string, string, IRedisSubscription> actionOnMessage)
{
var subscription = base.iClient.CreateSubscription();
subscription.OnSubscribe = c =>
{
Console.WriteLine($"订阅频道{c}");
Console.WriteLine();
};
subscription.OnUnSubscribe = c =>
{
Console.WriteLine($"取消订阅 {c}");
Console.WriteLine();
};
subscription.OnMessage += (c, s) =>
{
actionOnMessage(c, s, subscription);
};
Console.WriteLine($"开始启动监听 {channel}");
subscription.SubscribeToChannels(channel);
}
public void UnSubscribeFromChannels(string channel)
{
var subscription = base.iClient.CreateSubscription();
subscription.UnSubscribeFromChannels(channel);
}
#endregion
}
public class RedisSetService : RedisBase
{
#region 添加
public void Add(string key, string value)
{
base.iClient.AddItemToSet(key, value);
}
public void Add(string key, List<string> list)
{
base.iClient.AddRangeToSet(key, list);
}
#endregion
#region 获取
public string GetRandomItemFromSet(string key)
{
return base.iClient.GetRandomItemFromSet(key);
}
public long GetCount(string key)
{
return base.iClient.GetSetCount(key);
}
public HashSet<string> GetAllItemsFromSet(string key)
{
return base.iClient.GetAllItemsFromSet(key);
}
#endregion
#region 删除
public string RandomRemoveItemFromSet(string key)
{
return base.iClient.PopItemFromSet(key);
}
public void RemoveItemFromSet(string key, string value)
{
base.iClient.RemoveItemFromSet(key, value);
}
#endregion
#region 其它
public void MoveBetweenSets(string fromkey, string tokey, string value)
{
base.iClient.MoveBetweenSets(fromkey, tokey, value);
}
public HashSet<string> GetUnionFromSets(params string[] keys)
{
return base.iClient.GetUnionFromSets(keys);
}
public HashSet<string> GetIntersectFromSets(params string[] keys)
{
return base.iClient.GetIntersectFromSets(keys);
}
public HashSet<string> GetDifferencesFromSet(string fromKey, params string[] keys)
{
return base.iClient.GetDifferencesFromSet(fromKey,keys);
}
public void StoreUnionFromSets(string newkey, string[] keys)
{
base.iClient.StoreUnionFromSets(newkey, keys);
}
public void StoreDifferencesFromSet(string newkey, string fromkey, string[] keys)
{
base.iClient.StoreDifferencesFromSet(newkey, fromkey, keys);
}
#endregion
}
public class RedisStringService : RedisBase
{
#region 赋值
public bool Set<T>(string key, T value)
{
return base.iClient.Set<T>(key, value);
}
public bool Set<T>(string key, T value, DateTime dt)
{
return base.iClient.Set<T>(key, value, dt);
}
public bool Set<T>(string key, T value, TimeSpan sp)
{
return base.iClient.Set<T>(key, value, sp);
}
public void Set(Dictionary<string, string> dic)
{
base.iClient.SetAll(dic);
}
#endregion
#region 追加
public long Append(string key, string value)
{
return base.iClient.AppendToValue(key, value);
}
#endregion
#region 获取值
public string Get(string key)
{
return base.iClient.GetValue(key);
}
public List<string> Get(List<string> keys)
{
return base.iClient.GetValues(keys);
}
public List<T> Get<T>(List<string> keys)
{
return base.iClient.GetValues<T>(keys);
}
#endregion
#region 获取旧值赋上新值
public string GetAndSetValue(string key, string value)
{
return base.iClient.GetAndSetValue(key, value);
}
#endregion
#region 辅助方法
public long GetLength(string key)
{
return base.iClient.GetStringCount(key);
}
public long Incr(string key)
{
return base.iClient.IncrementValue(key);
}
public long IncrBy(string key, int count)
{
return base.iClient.IncrementValueBy(key, count);
}
public long Decr(string key)
{
return base.iClient.DecrementValue(key);
}
public long DecrBy(string key, int count)
{
return base.iClient.DecrementValueBy(key, count);
}
#endregion
}
public class RedisZSetService : RedisBase
{
#region 添加
public bool Add(string key, string value)
{
return base.iClient.AddItemToSortedSet(key, value);
}
public bool AddItemToSortedSet(string key, string value, double score)
{
return base.iClient.AddItemToSortedSet(key, value, score);
}
public bool AddRangeToSortedSet(string key, List<string> values, double score)
{
return base.iClient.AddRangeToSortedSet(key, values, score);
}
public bool AddRangeToSortedSet(string key, List<string> values, long score)
{
return base.iClient.AddRangeToSortedSet(key, values, score);
}
#endregion
#region 获取
public List<string> GetAll(string key)
{
return base.iClient.GetAllItemsFromSortedSet(key);
}
public List<string> GetAllDesc(string key)
{
return base.iClient.GetAllItemsFromSortedSetDesc(key);
}
public IDictionary<string, double> GetAllWithScoresFromSortedSet(string key)
{
return base.iClient.GetAllWithScoresFromSortedSet(key);
}
public long GetItemIndexInSortedSet(string key, string value)
{
return base.iClient.GetItemIndexInSortedSet(key, value);
}
public long GetItemIndexInSortedSetDesc(string key, string value)
{
return base.iClient.GetItemIndexInSortedSetDesc(key, value);
}
public double GetItemScoreInSortedSet(string key, string value)
{
return base.iClient.GetItemScoreInSortedSet(key, value);
}
public long GetSortedSetCount(string key)
{
return base.iClient.GetSortedSetCount(key);
}
public long GetSortedSetCount(string key, double fromScore, double toScore)
{
return base.iClient.GetSortedSetCount(key, fromScore, toScore);
}
public List<string> GetRangeFromSortedSetByHighestScore(string key, double fromscore, double toscore)
{
return base.iClient.GetRangeFromSortedSetByHighestScore(key, fromscore, toscore);
}
public List<string> GetRangeFromSortedSetByLowestScore(string key, double fromscore, double toscore)
{
return base.iClient.GetRangeFromSortedSetByLowestScore(key, fromscore, toscore);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByHighestScore(string key, double fromscore, double toscore)
{
return base.iClient.GetRangeWithScoresFromSortedSetByHighestScore(key, fromscore, toscore);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetByLowestScore(string key, double fromscore, double toscore)
{
return base.iClient.GetRangeWithScoresFromSortedSetByLowestScore(key, fromscore, toscore);
}
public List<string> GetRangeFromSortedSet(string key, int fromRank, int toRank)
{
return base.iClient.GetRangeFromSortedSet(key, fromRank, toRank);
}
public List<string> GetRangeFromSortedSetDesc(string key, int fromRank, int toRank)
{
return base.iClient.GetRangeFromSortedSetDesc(key, fromRank, toRank);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string key, int fromRank, int toRank)
{
return base.iClient.GetRangeWithScoresFromSortedSet(key, fromRank, toRank);
}
public IDictionary<string, double> GetRangeWithScoresFromSortedSetDesc(string key, int fromRank, int toRank)
{
return base.iClient.GetRangeWithScoresFromSortedSetDesc(key, fromRank, toRank);
}
#endregion
#region 删除
public bool RemoveItemFromSortedSet(string key, string value)
{
return base.iClient.RemoveItemFromSortedSet(key, value);
}
public long RemoveRangeFromSortedSet(string key, int minRank, int maxRank)
{
return base.iClient.RemoveRangeFromSortedSet(key, minRank, maxRank);
}
public long RemoveRangeFromSortedSetByScore(string key, double fromscore, double toscore)
{
return base.iClient.RemoveRangeFromSortedSetByScore(key, fromscore, toscore);
}
public string PopItemWithHighestScoreFromSortedSet(string key)
{
return base.iClient.PopItemWithHighestScoreFromSortedSet(key);
}
public string PopItemWithLowestScoreFromSortedSet(string key)
{
return base.iClient.PopItemWithLowestScoreFromSortedSet(key);
}
#endregion
#region 其它
public bool SortedSetContainsItem(string key, string value)
{
return base.iClient.SortedSetContainsItem(key, value);
}
public double IncrementItemInSortedSet(string key, string value, double scoreBy)
{
return base.iClient.IncrementItemInSortedSet(key, value, scoreBy);
}
public long StoreIntersectFromSortedSets(string newkey, string[] keys)
{
return base.iClient.StoreIntersectFromSortedSets(newkey, keys);
}
public long StoreUnionFromSortedSets(string newkey, string[] keys)
{
return base.iClient.StoreUnionFromSortedSets(newkey, keys);
}
#endregion
}
扩展版
internal class RedisManager
{
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();
internal static readonly string RedisSysCustomKey = ConfigurationManager.AppSettings["RedisSysCustomKey"];
internal static readonly int RedisDataBaseIndex = int.Parse(ConfigurationManager.AppSettings["RedisDataBaseIndex"]);
internal static readonly string RedisHostConnection = ConfigurationManager.AppSettings["RedisHostConnection"];
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
if (!ConnectionCache.ContainsKey(connectionString))
{
ConnectionCache[connectionString] = GetManager(connectionString);
}
return ConnectionCache[connectionString];
}
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisHostConnection;
var connect = ConnectionMultiplexer.Connect(connectionString);
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region 事件
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
}
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
}
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
}
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
}
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
}
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
}
#endregion 事件
}
public abstract class RedisBase : IDisposable
{
#region 属性字段
protected string CustomKey = RedisManager.RedisSysCustomKey;
protected readonly ConnectionMultiplexer _conn;
protected readonly IDatabase redis = null;
#endregion
#region 构造函数
protected RedisBase(int? dbNum = null)
{
_conn = RedisManager.Instance;
if (_conn != null)
{
redis = _conn.GetDatabase(dbNum ?? RedisManager.RedisDataBaseIndex);
}
else
{
throw new ArgumentNullException("Redis连接初始化失败");
}
}
private bool _disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this._disposed)
{
if (disposing)
{
_conn.Dispose();
}
}
this._disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion 构造函数
#region 外部调用静态方法
public static RedisStringService StringService => new RedisStringService();
public static RedisHashService HashService => new RedisHashService();
public static RedisListService ListService => new RedisListService();
public static RedisSetService SetService => new RedisSetService();
public static RedisSortedSetService SortedSetService => new RedisSortedSetService();
#endregion
#region 公共操作方法
#region 不建议公开这些方法,如果项目中用不到,建议注释或者删除
public ITransaction CreateTransaction() => redis.CreateTransaction();
public IDatabase GetDatabase() => redis;
public IServer GetServer(string hostAndPort) => _conn.GetServer(hostAndPort);
public bool RedisTransaction(Action<ITransaction> act)
{
var tran = redis.CreateTransaction();
act.Invoke(tran);
bool committed = tran.Execute();
return committed;
}
public void RedisLockTake(Action act, TimeSpan ts)
{
RedisValue token = Environment.MachineName;
string lockKey = "lock_LockTake";
if (redis.LockTake(lockKey, token, ts))
{
try
{
act();
}
finally
{
redis.LockRelease(lockKey, token);
}
}
}
#endregion 其他
#region 常用Key操作
public void SetSysCustomKey(string customKey) => CustomKey = customKey;
public string AddSysCustomKey(string oldKey) => $"{CustomKey}_{oldKey}";
#region 同步方法
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return redis.KeyDelete(key);
}
public long KeyDelete(params string[] keys)
{
RedisKey[] newKeys = keys.Select(o => (RedisKey)AddSysCustomKey(o)).ToArray();
return redis.KeyDelete(newKeys);
}
public void KeyFulsh()
{
redis.Execute("FLUSHDB");
}
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return redis.KeyExists(key);
}
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
newKey = AddSysCustomKey(newKey);
return redis.KeyRename(key, newKey);
}
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return redis.KeyExpire(key, expiry);
}
#endregion
#region 异步方法
public async Task<bool> KeyDeleteAsync(string key)
{
key = AddSysCustomKey(key);
return await redis.KeyDeleteAsync(key);
}
public async Task<long> KeyDeleteAsync(params string[] keys)
{
RedisKey[] newKeys = keys.Select(o => (RedisKey)AddSysCustomKey(o)).ToArray();
return await redis.KeyDeleteAsync(newKeys);
}
public async Task KeyFulshAsync()
{
await redis.ExecuteAsync("FLUSHDB");
}
public async Task<bool> KeyExistsAsync(string key)
{
key = AddSysCustomKey(key);
return await redis.KeyExistsAsync(key);
}
public async Task<bool> KeyRenameAsync(string key, string newKey)
{
key = AddSysCustomKey(key);
newKey = AddSysCustomKey(newKey);
return await redis.KeyRenameAsync(key, newKey);
}
public async Task<bool> KeyExpireAsync(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await redis.KeyExpireAsync(key, expiry);
}
#endregion
#endregion
#endregion
#region 辅助方法
protected string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() :
JsonConvert.SerializeObject(value, Formatting.None);
return result;
}
protected T ConvertObj<T>(RedisValue value)
{
return value.IsNullOrEmpty ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
protected List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
}
protected RedisKey[] ConvertRedisKeys(List<string> redisKeys) => redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
protected RedisKey[] ConvertRedisKeys(params string[] redisKeys) => redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
protected RedisKey[] ConvertRedisKeysAddSysCustomKey(params string[] redisKeys) => redisKeys.Select(redisKey => (RedisKey)AddSysCustomKey(redisKey)).ToArray();
protected RedisValue[] ConvertRedisValue<T>(params T[] redisValues) => redisValues.Select(o => (RedisValue)ConvertJson<T>(o)).ToArray();
#endregion 辅助方法
}
服务层:五大数据结构
public class RedisHashService : RedisBase
{
#region 构造函数
public RedisHashService(int? dbNum = null) :
base(dbNum)
{ }
#endregion
#region 同步方法
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return base.redis.HashExists(key, dataKey);
}
public bool HashSet<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
string json = ConvertJson(t);
return base.redis.HashSet(key, dataKey, json);
}
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return base.redis.HashDelete(key, dataKey);
}
public long HashDelete(string key, params string[] dataKeys)
{
key = AddSysCustomKey(key);
var newValues = dataKeys.Select(o => (RedisValue)o).ToArray();
return base.redis.HashDelete(key, newValues);
}
public T HashGet<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = base.redis.HashGet(key, dataKey);
return ConvertObj<T>(value);
}
public double HashIncrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return base.redis.HashIncrement(key, dataKey, val);
}
public double HashDecrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return base.redis.HashDecrement(key, dataKey, val);
}
public string[] HashKeys(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = base.redis.HashKeys(key);
return values.Select(o=>o.ToString()).ToArray();
}
public Dictionary<string, T> HashGetAll<T>(string key)
{
key = AddSysCustomKey(key);
var query = base.redis.HashGetAll(key);
Dictionary<string, T> dic = new Dictionary<string, T>();
foreach (var item in query)
{
dic.Add(item.Name, ConvertObj<T>(item.Value));
}
return dic;
}
#endregion 同步方法
#region 异步方法
public async Task<bool> HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await base.redis.HashExistsAsync(key, dataKey);
}
public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
string json = ConvertJson(t);
return await base.redis.HashSetAsync(key, dataKey, json);
}
public async Task<bool> HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await base.redis.HashDeleteAsync(key, dataKey);
}
public async Task<long> HashDeleteAsync(string key, params string[] dataKeys)
{
key = AddSysCustomKey(key);
var newValues = dataKeys.Select(o => (RedisValue)o).ToArray();
return await base.redis.HashDeleteAsync(key, newValues);
}
public async Task<T> HashGetAsync<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await base.redis.HashGetAsync(key, dataKey);
return ConvertObj<T>(value);
}
public async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await base.redis.HashIncrementAsync(key, dataKey, val);
}
public async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await base.redis.HashDecrementAsync(key, dataKey, val);
}
public async Task<string[]> HashKeysAsync(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await base.redis.HashKeysAsync(key);
return values.Select(o => o.ToString()).ToArray();
}
public async Task<Dictionary<string, T>> HashGetAllAsync<T>(string key)
{
key = AddSysCustomKey(key);
var query = await base.redis.HashGetAllAsync(key);
Dictionary<string, T> dic = new Dictionary<string, T>();
foreach (var item in query)
{
dic.Add(item.Name, ConvertObj<T>(item.Value));
}
return dic;
}
#endregion 异步方法
}
public class RedisListService : RedisBase
{
#region 构造函数
public RedisListService(int? dbNum = null) :
base(dbNum)
{ }
#endregion
#region 同步方法
public long ListLeftPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return base.redis.ListLeftPush(key, jValue);
}
public long ListLeftPush<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return base.redis.ListLeftPush(key, valueList);
}
public long ListRightPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return base.redis.ListRightPush(key, jValue);
}
public long ListRightPush<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return base.redis.ListRightPush(key, valueList);
}
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.ListLeftPop(key);
return base.ConvertObj<T>(rValue);
}
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.ListRightPop(key);
return base.ConvertObj<T>(rValue);
}
public T ListRightPopLeftPush<T>(string key, string destination)
{
key = AddSysCustomKey(key);
destination = AddSysCustomKey(destination);
var rValue = base.redis.ListRightPopLeftPush(key, destination);
return base.ConvertObj<T>(rValue);
}
public long ListInsertAfter<T>(string key, T pivot, T value)
{
key = AddSysCustomKey(key);
string pValue = ConvertJson(pivot);
string jValue = ConvertJson(value);
return base.redis.ListInsertAfter(key, pValue, jValue);
}
public long ListInsertBefore<T>(string key, T pivot, T value)
{
key = AddSysCustomKey(key);
string pValue = ConvertJson(pivot);
string jValue = ConvertJson(value);
return base.redis.ListInsertBefore(key, pValue, jValue);
}
public List<T> ListRange<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.ListRange(key);
return base.ConvetList<T>(rValue);
}
public T ListGetByIndex<T>(string key, long index)
{
key = AddSysCustomKey(key);
var rValue = base.redis.ListGetByIndex(key, index);
return base.ConvertObj<T>(rValue);
}
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return base.redis.ListLength(key);
}
public long ListRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return base.redis.ListRemove(key, jValue);
}
#endregion
#region 异步方法
public async Task<long> ListLeftPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return await base.redis.ListLeftPushAsync(key, jValue);
}
public async Task<long> ListLeftPushAsync<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return await base.redis.ListLeftPushAsync(key, valueList);
}
public async Task<long> ListRightPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return await base.redis.ListRightPushAsync(key, jValue);
}
public async Task<long> ListRightPushAsync<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return await base.redis.ListRightPushAsync(key, valueList);
}
public async Task<T> ListLeftPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.ListLeftPopAsync(key);
return base.ConvertObj<T>(rValue);
}
public async Task<T> ListRightPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.ListRightPopAsync(key);
return base.ConvertObj<T>(rValue);
}
public async Task<T> ListRightPopLeftPushAsync<T>(string key, string destination)
{
key = AddSysCustomKey(key);
destination = AddSysCustomKey(destination);
var rValue = await base.redis.ListRightPopLeftPushAsync(key, destination);
return base.ConvertObj<T>(rValue);
}
public async Task<long> ListInsertAfterAsync<T>(string key, T pivot, T value)
{
key = AddSysCustomKey(key);
string pValue = ConvertJson(pivot);
string jValue = ConvertJson(value);
return await base.redis.ListInsertAfterAsync(key, pValue, jValue);
}
public async Task<long> ListInsertBeforeAsync<T>(string key, T pivot, T value)
{
key = AddSysCustomKey(key);
string pValue = ConvertJson(pivot);
string jValue = ConvertJson(value);
return await base.redis.ListInsertBeforeAsync(key, pValue, jValue);
}
public async Task<List<T>> ListRangeAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.ListRangeAsync(key);
return base.ConvetList<T>(rValue);
}
public async Task<T> ListGetByIndexAsync<T>(string key, long index)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.ListGetByIndexAsync(key, index);
return base.ConvertObj<T>(rValue);
}
public async Task<long> ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await base.redis.ListLengthAsync(key);
}
public async Task<long> ListRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return await base.redis.ListRemoveAsync(key, jValue);
}
#endregion
}
public class RedisSetService : RedisBase
{
#region 构造函数
public RedisSetService(int? dbNum = null) :
base(dbNum)
{ }
#endregion
#region 同步方法
public bool SetAdd<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return base.redis.SetAdd(key, jValue);
}
public long SetAdd<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return base.redis.SetAdd(key, valueList);
}
public long SetLength(string key)
{
key = AddSysCustomKey(key);
return base.redis.SetLength(key);
}
public bool SetContains<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return base.redis.SetContains(key, jValue);
}
public T SetRandomMember<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.SetRandomMember(key);
return ConvertObj<T>(rValue);
}
public List<T> SetMembers<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.SetMembers(key);
return ConvetList<T>(rValue);
}
public long SetRemove<T>(string key, params T[] value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value);
return base.redis.SetRemove(key, valueList);
}
public T SetPop<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = base.redis.SetPop(key);
return ConvertObj<T>(rValue);
}
public List<T> SetCombineUnion<T>(params string[] keys)
{
return _SetCombine<T>(SetOperation.Union, keys);
}
public List<T> SetCombineIntersect<T>(params string[] keys)
{
return _SetCombine<T>(SetOperation.Intersect, keys);
}
public List<T> SetCombineDifference<T>(params string[] keys)
{
return _SetCombine<T>(SetOperation.Difference, keys);
}
public long SetCombineUnionAndStore(string destination, params string[] keys)
{
return _SetCombineAndStore(SetOperation.Union, destination, keys);
}
public long SetCombineIntersectAndStore(string destination, params string[] keys)
{
return _SetCombineAndStore(SetOperation.Intersect, destination, keys);
}
public long SetCombineDifferenceAndStore(string destination, params string[] keys)
{
return _SetCombineAndStore(SetOperation.Difference, destination, keys);
}
#endregion
#region 异步方法
public async Task<bool> SetAddAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return await base.redis.SetAddAsync(key, jValue);
}
public async Task<long> SetAddAsync<T>(string key, List<T> value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value.ToArray());
return await base.redis.SetAddAsync(key, valueList);
}
public async Task<long> SetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await base.redis.SetLengthAsync(key);
}
public async Task<bool> SetContainsAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jValue = ConvertJson(value);
return await base.redis.SetContainsAsync(key, jValue);
}
public async Task<T> SetRandomMemberAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.SetRandomMemberAsync(key);
return ConvertObj<T>(rValue);
}
public async Task<List<T>> SetMembersAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.SetMembersAsync(key);
return ConvetList<T>(rValue);
}
public async Task<long> SetRemoveAsync<T>(string key, params T[] value)
{
key = AddSysCustomKey(key);
RedisValue[] valueList = base.ConvertRedisValue(value);
return await base.redis.SetRemoveAsync(key, valueList);
}
public async Task<T> SetPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var rValue = await base.redis.SetPopAsync(key);
return ConvertObj<T>(rValue);
}
public async Task<List<T>> SetCombineUnionAsync<T>(params string[] keys)
{
return await _SetCombineAsync<T>(SetOperation.Union, keys);
}
public async Task<List<T>> SetCombineIntersectAsync<T>(params string[] keys)
{
return await _SetCombineAsync<T>(SetOperation.Intersect, keys);
}
public async Task<List<T>> SetCombineDifferenceAsync<T>(params string[] keys)
{
return await _SetCombineAsync<T>(SetOperation.Difference, keys);
}
public async Task<long> SetCombineUnionAndStoreAsync(string destination, params string[] keys)
{
return await _SetCombineAndStoreAsync(SetOperation.Union, destination, keys);
}
public async Task<long> SetCombineIntersectAndStoreAsync(string destination, params string[] keys)
{
return await _SetCombineAndStoreAsync(SetOperation.Intersect, destination, keys);
}
public async Task<long> SetCombineDifferenceAndStoreAsync(string destination, params string[] keys)
{
return await _SetCombineAndStoreAsync(SetOperation.Difference, destination, keys);
}
#endregion
#region 内部辅助方法
private List<T> _SetCombine<T>(SetOperation operation, params string[] keys)
{
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
var rValue = base.redis.SetCombine(operation, keyList);
return ConvetList<T>(rValue);
}
private long _SetCombineAndStore(SetOperation operation, string destination, params string[] keys)
{
destination = AddSysCustomKey(destination);
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
return base.redis.SetCombineAndStore(operation, destination, keyList);
}
private async Task<List<T>> _SetCombineAsync<T>(SetOperation operation, params string[] keys)
{
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
var rValue = await base.redis.SetCombineAsync(operation, keyList);
return ConvetList<T>(rValue);
}
private async Task<long> _SetCombineAndStoreAsync(SetOperation operation, string destination, params string[] keys)
{
destination = AddSysCustomKey(destination);
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
return await base.redis.SetCombineAndStoreAsync(operation, destination, keyList);
}
#endregion
}
public class RedisSortedSetService : RedisBase
{
#region 构造函数
public RedisSortedSetService(int? dbNum = null) :
base(dbNum)
{ }
#endregion
#region 同步方法
public bool SortedSetAdd<T>(string key, T value, double? score = null)
{
key = AddSysCustomKey(key);
double scoreNum = score ?? _GetScore(key);
return base.redis.SortedSetAdd(key, ConvertJson<T>(value), scoreNum);
}
public long SortedSetAdd<T>(string key, List<T> value, double? score = null)
{
key = AddSysCustomKey(key);
double scoreNum = score ?? _GetScore(key);
SortedSetEntry[] rValue = value.Select(o => new SortedSetEntry(ConvertJson<T>(o), scoreNum++)).ToArray();
return base.redis.SortedSetAdd(key, rValue);
}
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return redis.SortedSetLength(key);
}
public long SortedSetLengthByValue<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
return redis.SortedSetLengthByValue(key, sValue, eValue);
}
public double? SortedSetScore<T>(string key, T value)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return redis.SortedSetScore(key, rValue);
}
public double SortedSetMinScore(string key)
{
key = AddSysCustomKey(key);
double dValue = 0;
var rValue = base.redis.SortedSetRangeByRankWithScores(key, 0, 0, Order.Ascending).FirstOrDefault();
dValue = rValue != null ? rValue.Score : 0;
return dValue;
}
public double SortedSetMaxScore(string key)
{
key = AddSysCustomKey(key);
double dValue = 0;
var rValue = base.redis.SortedSetRangeByRankWithScores(key, 0, 0, Order.Descending).FirstOrDefault();
dValue = rValue != null ? rValue.Score : 0;
return dValue;
}
public long SortedSetRemove<T>(string key, params T[] value)
{
key = AddSysCustomKey(key);
var rValue = ConvertRedisValue<T>(value);
return base.redis.SortedSetRemove(key, rValue);
}
public long SortedSetRemoveRangeByValue<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
return base.redis.SortedSetRemoveRangeByValue(key, sValue, eValue);
}
public long SortedSetRemoveRangeByRank(string key, long start, long stop)
{
key = AddSysCustomKey(key);
return base.redis.SortedSetRemoveRangeByRank(key, start, stop);
}
public long SortedSetRemoveRangeByScore(string key, double start, double stop)
{
key = AddSysCustomKey(key);
return base.redis.SortedSetRemoveRangeByScore(key, start, stop);
}
public List<T> SortedSetRangeByRank<T>(string key, long start = 0, long stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = base.redis.SortedSetRangeByRank(key, start, stop, orderBy);
return ConvetList<T>(rValue);
}
public Dictionary<T, double> SortedSetRangeByRankWithScores<T>(string key, long start = 0, long stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = base.redis.SortedSetRangeByRankWithScores(key, start, stop, orderBy);
Dictionary<T, double> dicList = new Dictionary<T, double>();
foreach (var item in rValue)
{
dicList.Add(ConvertObj<T>(item.Element), item.Score);
}
return dicList;
}
public List<T> SortedSetRangeByScore<T>(string key, double start = 0, double stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = base.redis.SortedSetRangeByScore(key, start, stop, Exclude.None, orderBy);
return ConvetList<T>(rValue);
}
public Dictionary<T, double> SortedSetRangeByScoreWithScores<T>(string key, double start = 0, double stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = base.redis.SortedSetRangeByScoreWithScores(key, start, stop, Exclude.None, orderBy);
Dictionary<T, double> dicList = new Dictionary<T, double>();
foreach (var item in rValue)
{
dicList.Add(ConvertObj<T>(item.Element), item.Score);
}
return dicList;
}
public List<T> SortedSetRangeByValue<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
var rValue = base.redis.SortedSetRangeByValue(key, sValue, eValue);
return ConvetList<T>(rValue);
}
public long SortedSetCombineUnionAndStore(string destination, params string[] keys)
{
return _SortedSetCombineAndStore(SetOperation.Union, destination, keys);
}
public long SortedSetCombineIntersectAndStore(string destination, params string[] keys)
{
return _SortedSetCombineAndStore(SetOperation.Intersect, destination, keys);
}
public double SortedSetDecrement<T>(string key, T value, double scores)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return redis.SortedSetDecrement(key, rValue, scores);
}
public double SortedSetIncrement<T>(string key, T value, double scores)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return redis.SortedSetIncrement(key, rValue, scores);
}
#endregion
#region 异步方法
public async Task<bool> SortedSetAddAsync<T>(string key, T value, double? score = null)
{
key = AddSysCustomKey(key);
double scoreNum = score ?? _GetScore(key);
return await base.redis.SortedSetAddAsync(key, ConvertJson<T>(value), scoreNum);
}
public async Task<long> SortedSetAddAsync<T>(string key, List<T> value, double? score = null)
{
key = AddSysCustomKey(key);
double scoreNum = score ?? _GetScore(key);
SortedSetEntry[] rValue = value.Select(o => new SortedSetEntry(ConvertJson<T>(o), scoreNum++)).ToArray();
return await base.redis.SortedSetAddAsync(key, rValue);
}
public async Task<long> SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await redis.SortedSetLengthAsync(key);
}
public async Task<long> SortedSetLengthByValueAsync<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
return await redis.SortedSetLengthByValueAsync(key, sValue, eValue);
}
public async Task<double?> SortedSetScoreAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return await redis.SortedSetScoreAsync(key, rValue);
}
public async Task<double> SortedSetMinScoreAsync(string key)
{
key = AddSysCustomKey(key);
double dValue = 0;
var rValue = (await base.redis.SortedSetRangeByRankWithScoresAsync(key, 0, 0, Order.Ascending)).FirstOrDefault();
dValue = rValue != null ? rValue.Score : 0;
return dValue;
}
public async Task<double> SortedSetMaxScoreAsync(string key)
{
key = AddSysCustomKey(key);
double dValue = 0;
var rValue = (await base.redis.SortedSetRangeByRankWithScoresAsync(key, 0, 0, Order.Descending)).FirstOrDefault();
dValue = rValue != null ? rValue.Score : 0;
return dValue;
}
public async Task<long> SortedSetRemoveAsync<T>(string key, params T[] value)
{
key = AddSysCustomKey(key);
var rValue = ConvertRedisValue<T>(value);
return await base.redis.SortedSetRemoveAsync(key, rValue);
}
public async Task<long> SortedSetRemoveRangeByValueAsync<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
return await base.redis.SortedSetRemoveRangeByValueAsync(key, sValue, eValue);
}
public async Task<long> SortedSetRemoveRangeByRankAsync(string key, long start, long stop)
{
key = AddSysCustomKey(key);
return await base.redis.SortedSetRemoveRangeByRankAsync(key, start, stop);
}
public async Task<long> SortedSetRemoveRangeByScoreAsync(string key, double start, double stop)
{
key = AddSysCustomKey(key);
return await base.redis.SortedSetRemoveRangeByScoreAsync(key, start, stop);
}
public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key, long start = 0, long stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = await base.redis.SortedSetRangeByRankAsync(key, start, stop, orderBy);
return ConvetList<T>(rValue);
}
public async Task<Dictionary<T, double>> SortedSetRangeByRankWithScoresAsync<T>(string key, long start = 0, long stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = await base.redis.SortedSetRangeByRankWithScoresAsync(key, start, stop, orderBy);
Dictionary<T, double> dicList = new Dictionary<T, double>();
foreach (var item in rValue)
{
dicList.Add(ConvertObj<T>(item.Element), item.Score);
}
return dicList;
}
public async Task<List<T>> SortedSetRangeByScoreAsync<T>(string key, double start = 0, double stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = await base.redis.SortedSetRangeByScoreAsync(key, start, stop, Exclude.None, orderBy);
return ConvetList<T>(rValue);
}
public async Task<Dictionary<T, double>> SortedSetRangeByScoreWithScoresAsync<T>(string key, double start = 0, double stop = -1, bool desc = false)
{
key = AddSysCustomKey(key);
Order orderBy = desc ? Order.Descending : Order.Ascending;
var rValue = await base.redis.SortedSetRangeByScoreWithScoresAsync(key, start, stop, Exclude.None, orderBy);
Dictionary<T, double> dicList = new Dictionary<T, double>();
foreach (var item in rValue)
{
dicList.Add(ConvertObj<T>(item.Element), item.Score);
}
return dicList;
}
public async Task<List<T>> SortedSetRangeByValueAsync<T>(string key, T startValue, T endValue)
{
key = AddSysCustomKey(key);
var sValue = ConvertJson<T>(startValue);
var eValue = ConvertJson<T>(endValue);
var rValue = await base.redis.SortedSetRangeByValueAsync(key, sValue, eValue);
return ConvetList<T>(rValue);
}
public async Task<long> SortedSetCombineUnionAndStoreAsync(string destination, params string[] keys)
{
return await _SortedSetCombineAndStoreAsync(SetOperation.Union, destination, keys);
}
public async Task<long> SortedSetCombineIntersectAndStoreAsync(string destination, params string[] keys)
{
return await _SortedSetCombineAndStoreAsync(SetOperation.Intersect, destination, keys);
}
public async Task<double> SortedSetDecrementAsync<T>(string key, T value, double scores)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return await base.redis.SortedSetDecrementAsync(key, rValue, scores);
}
public async Task<double> SortedSetIncrementAsync<T>(string key, T value, double scores)
{
key = AddSysCustomKey(key);
var rValue = ConvertJson<T>(value);
return await base.redis.SortedSetIncrementAsync(key, rValue, scores);
}
#endregion
#region 内部辅助方法
private double _GetScore(string key)
{
double dValue = 0;
var rValue = base.redis.SortedSetRangeByRankWithScores(key, 0, 0, Order.Descending).FirstOrDefault();
dValue = rValue != null ? rValue.Score : 0;
return dValue + 1;
}
private long _SortedSetCombineAndStore(SetOperation operation, string destination, params string[] keys)
{
#region 查看源码,似乎并不支持Difference
#endregion
destination = AddSysCustomKey(destination);
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
var rValue = base.redis.SortedSetCombineAndStore(operation, destination, keyList);
return rValue;
}
private async Task<long> _SortedSetCombineAndStoreAsync(SetOperation operation, string destination, params string[] keys)
{
destination = AddSysCustomKey(destination);
RedisKey[] keyList = base.ConvertRedisKeysAddSysCustomKey(keys);
var rValue = await base.redis.SortedSetCombineAndStoreAsync(operation, destination, keyList);
return rValue;
}
#endregion
}
public class RedisStringService : RedisBase
{
#region 构造函数
public RedisStringService(int? dbNum = null) :
base(dbNum)
{ }
#endregion
#region 同步方法
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return base.redis.StringSet(key, value, expiry);
}
public bool StringSet(Dictionary<string, string> valueList)
{
var newkeyValues = valueList.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToArray();
return base.redis.StringSet(newkeyValues);
}
public bool StringSet<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string jsonValue = ConvertJson(value);
return base.redis.StringSet(key, jsonValue, expiry);
}
public long StringAppend(string key, string value)
{
key = AddSysCustomKey(key);
return base.redis.StringAppend(key, value);
}
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return base.redis.StringGet(key);
}
public List<string> StringGet(params string[] keys)
{
var newKeys = ConvertRedisKeysAddSysCustomKey(keys);
var values = base.redis.StringGet(newKeys);
return values.Select(o => o.ToString()).ToList();
}
public T StringGet<T>(string key)
{
key = AddSysCustomKey(key);
var values = base.redis.StringGet(key);
return ConvertObj<T>(values);
}
public List<T> StringGet<T>(params string[] keys)
{
var newKeys = ConvertRedisKeysAddSysCustomKey(keys);
var values = base.redis.StringGet(newKeys);
return ConvetList<T>(values);
}
public string StringGetSet(string key, string value)
{
key = AddSysCustomKey(key);
return base.redis.StringGetSet(key, value);
}
public T StringGetSet<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jsonValue = ConvertJson(value);
var oValue = base.redis.StringGetSet(key, jsonValue);
return ConvertObj<T>(oValue);
}
public long StringGetLength(string key)
{
key = AddSysCustomKey(key);
return base.redis.StringLength(key);
}
public double StringIncrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return base.redis.StringIncrement(key, val);
}
public double StringDecrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return base.redis.StringDecrement(key, val);
}
#endregion
#region 异步方法
public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await base.redis.StringSetAsync(key, value, expiry);
}
public async Task<bool> StringSetAsync(Dictionary<string, string> valueList)
{
var newkeyValues = valueList.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToArray();
return await base.redis.StringSetAsync(newkeyValues);
}
public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string jsonValue = ConvertJson(obj);
return await base.redis.StringSetAsync(key, jsonValue, expiry);
}
public async Task<long> StringAppendAsync(string key, string value)
{
key = AddSysCustomKey(key);
return await base.redis.StringAppendAsync(key, value);
}
public async Task<string> StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await base.redis.StringGetAsync(key);
}
public async Task<List<string>> StringGetAsync(params string[] keys)
{
var newKeys = ConvertRedisKeysAddSysCustomKey(keys);
var values = await base.redis.StringGetAsync(newKeys);
return values.Select(o => o.ToString()).ToList();
}
public async Task<T> StringGetAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await base.redis.StringGetAsync(key);
return ConvertObj<T>(values);
}
public async Task<List<T>> StringGetAsync<T>(params string[] keys)
{
var newKeys = ConvertRedisKeysAddSysCustomKey(keys);
var values = await base.redis.StringGetAsync(newKeys);
return ConvetList<T>(values);
}
public async Task<string> StringGetSetAsync(string key, string value)
{
key = AddSysCustomKey(key);
return await base.redis.StringGetSetAsync(key, value);
}
public async Task<T> StringGetSetAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
string jsonValue = ConvertJson(value);
var oValue = await base.redis.StringGetSetAsync(key, jsonValue);
return ConvertObj<T>(oValue);
}
public async Task<long> StringGetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await base.redis.StringLengthAsync(key);
}
public async Task<double> StringIncrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await base.redis.StringIncrementAsync(key, val);
}
public async Task<double> StringDecrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await base.redis.StringDecrementAsync(key, val);
}
#endregion
}