DB|Redis快速入手,NET起跑
Redis可以完美實現快取記憶體的功能,同時也具備了資料庫的所有技能(Redis稱之為資料持久化)。前者可以秒掉memcached,後者原則上可以替代傳統資料庫,但鑑於Mysql,SQL Server,Oracle等關係型資料庫所佔領的領地非常廣泛,處理的問題相當複雜,Redis要完全取而代之,尚需時日。事實上,任何一種技術都無法獨步天下,我們只是擇其善者而用之。
可以肯定的是,Redis在資料快取和儲存方面確實有著不可比擬的優勢,在傳統資料庫難顧首位的應用場景裡,Redis大放異彩。
1)熱點資料(快取)
熱點資料(經常會被查詢,但極少變更的資料),大量密集的訪問對速度和定位都由著較高的要求,QPS和極強的穩定性成為reidis的必殺技。
2)計數器
傳統DB在處理併發訪問時,可能存在髒讀的情況,Redis採用單執行緒,可以避免併發問題,同時保證100%毫秒級效能。
3)佇列
4)位操作
5)分散式鎖與單執行緒機制
關於佇列和計數等操作,已在文末提供的工具類中加以封裝,可以直接取用。
1.下載
官方網站 https://redis.io/
官方網站(中) http://www.redis.cn/
入門文件 http://www.runoob.com/redis/redis-tutorial.html
建議去github下載 https://github.com/MicrosoftArchive/redis/releases
安裝過程非常簡單,下載解壓縮後,命令列定位到相應目錄執行命令就可以了,github很貼心地打了包,也可以直接執行他們的安裝程式。
安裝成功的介面如下:
2.配置
由於我此前已經安裝過,所以顯示埠被佔用了。
關於資料庫的預設埠,記住這個就可以了。
密碼設定 config set requirepass test123
用過MySQL的同學是不是感到很親切,熟悉的套路熟悉的感覺,沒錯,和MySQL一樣,Redis也有較為成熟的管理工具,我選擇了redisdesktop,下載地址 https://redisdesktop.com/,介面非常友好。
更多設定可以參考 http://www.runoob.com/redis/redis-install.html
3.測試
4.工具及API
Redis非常良心的一點是提供了豐富而強大的api支援,作為C#從業人員,本次分享C#的兩個工具類,需要的話可以直接取用。工具類依賴於StackExchange.Redis包,請使用nuget自行安裝。
RedisConnectionHelp .cs
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Configuration;
namespace RedisHelper
{
/// <summary>
/// ConnectionMultiplexer物件管理幫助類
/// </summary>
public static class RedisConnectionHelp
{
//系統自定義Key字首
public static readonly string SysCustomKey = ConfigurationManager.AppSettings["RedisKey"] ?? "";
//"127.0.0.1:6379,allowadmin=true
private static readonly string RedisConnectionString = ConfigurationManager.AppSettings["RedisExchangeHosts"];
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();
/// <summary>
/// 單例獲取
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
/// <summary>
/// 快取獲取
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
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 ?? RedisConnectionString;
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 事件
/// <summary>
/// 配置更改時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 發生錯誤時
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立連線之前的錯誤
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 連線失敗 , 如果重新連線成功你將不會收到這個通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("重新連線:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改叢集
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis類庫錯誤
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
}
RedisHelper .cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace RedisUtil
{
/// <summary>
/// Redis操作
/// </summary>
public class RedisHelper
{
private int DbNum { get; set; }
private readonly ConnectionMultiplexer _conn;
public string CustomKey;
#region 建構函式
public RedisHelper(int dbNum = 0)
: this(dbNum, null)
{
}
public RedisHelper(int dbNum, string readWriteHosts)
{
DbNum = dbNum;
_conn =
string.IsNullOrWhiteSpace(readWriteHosts) ?
RedisConnectionHelp.Instance :
RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
}
#endregion 建構函式
#region String
#region 同步方法
/// <summary>
/// 儲存單個key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">儲存的值</param>
/// <param name="expiry">過期時間</param>
/// <returns></returns>
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.StringSet(key, value, expiry));
}
/// <summary>
/// 儲存多個key value
/// </summary>
/// <param name="keyValues">鍵值對</param>
/// <returns></returns>
public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return Do(db => db.StringSet(newkeyValues.ToArray()));
}
/// <summary>
/// 儲存一個物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return Do(db => db.StringSet(key, json, expiry));
}
/// <summary>
/// 獲取單個key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.StringGet(key));
}
/// <summary>
/// 獲取多個Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public RedisValue[] StringGet(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 獲取一個key的物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T StringGet<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db => ConvertObj<T>(db.StringGet(key)));
}
/// <summary>
/// 為數字增長val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以為負</param>
/// <returns>增長後的值</returns>
public double StringIncrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringIncrement(key, val));
}
/// <summary>
/// 為數字減少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以為負</param>
/// <returns>減少後的值</returns>
public double StringDecrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringDecrement(key, val));
}
#endregion 同步方法
#region 非同步方法
/// <summary>
/// 儲存單個key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">儲存的值</param>
/// <param name="expiry">過期時間</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await Do(db => db.StringSetAsync(key, value, expiry));
}
/// <summary>
/// 儲存多個key value
/// </summary>
/// <param name="keyValues">鍵值對</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
}
/// <summary>
/// 儲存一個物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return await Do(db => db.StringSetAsync(key, json, expiry));
}
/// <summary>
/// 獲取單個key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public async Task<string> StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringGetAsync(key));
}
/// <summary>
/// 獲取多個Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public async Task<RedisValue[]> StringGetAsync(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 獲取一個key的物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> StringGetAsync<T>(string key)
{
key = AddSysCustomKey(key);
string result = await Do(db => db.StringGetAsync(key));
return ConvertObj<T>(result);
}
/// <summary>
/// 為數字增長val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以為負</param>
/// <returns>增長後的值</returns>
public async Task<double> StringIncrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringIncrementAsync(key, val));
}
/// <summary>
/// 為數字減少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以為負</param>
/// <returns>減少後的值</returns>
public async Task<double> StringDecrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringDecrementAsync(key, val));
}
#endregion 非同步方法
#endregion String
#region Hash
#region 同步方法
/// <summary>
/// 判斷某個資料是否已經被快取
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashExists(key, dataKey));
}
/// <summary>
/// 儲存資料到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string json = ConvertJson(t);
return db.HashSet(key, dataKey, json);
});
}
/// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDelete(key, dataKey));
}
/// <summary>
/// 移除hash中的多個值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public long HashDelete(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return Do(db => db.HashDelete(key, dataKeys.ToArray()));
}
/// <summary>
/// 從hash表獲取資料
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public T HashGet<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 為數字增長val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以為負</param>
/// <returns>增長後的值</returns>
public double HashIncrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashIncrement(key, dataKey, val));
}
/// <summary>
/// 為數字減少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以為負</param>
/// <returns>減少後的值</returns>
public double HashDecrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDecrement(key, dataKey, val));
}
/// <summary>
/// 獲取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> HashKeys<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
RedisValue[] values = db.HashKeys(key);
return ConvetList<T>(values);
});
}
#endregion 同步方法
#region 非同步方法
/// <summary>
/// 判斷某個資料是否已經被快取
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashExistsAsync(key, dataKey));
}
/// <summary>
/// 儲存資料到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return await Do(db =>
{
string json = ConvertJson(t);
return db.HashSetAsync(key, dataKey, json);
});
}
/// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDeleteAsync(key, dataKey));
}
/// <summary>
/// 移除hash中的多個值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
}
/// <summary>
/// 從hash表獲取資料
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<T> HashGeAsync<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await Do(db => db.HashGetAsync(key, dataKey));
return ConvertObj<T>(value);
}
/// <summary>
/// 為數字增長val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以為負</param>
/// <returns>增長後的值</returns>
public async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashIncrementAsync(key, dataKey, val));
}
/// <summary>
/// 為數字減少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以為負</param>
/// <returns>減少後的值</returns>
public async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDecrementAsync(key, dataKey, val));
}
/// <summary>
/// 獲取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> HashKeysAsync<T>(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await Do(db => db.HashKeysAsync(key));
return ConvetList<T>(values);
}
#endregion 非同步方法
#endregion Hash
#region List
#region 同步方法
/// <summary>
/// 移除指定ListId的內部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRemove(key, ConvertJson(value)));
}
/// <summary>
/// 獲取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> ListRange<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvetList<T>(values);
});
}
/// <summary>
/// 入隊
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, ConvertJson(value)));
}
/// <summary>
/// 出隊
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 入棧
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListLeftPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListLeftPush(key, ConvertJson(value)));
}
/// <summary>
/// 出棧
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 獲取集合中的數量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.ListLength(key));
}
#endregion 同步方法
#region 非同步方法
/// <summary>
/// 移除指定ListId的內部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
}
/// <summary>
/// 獲取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> ListRangeAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.ListRangeAsync(key));
return ConvetList<T>(values);
}
/// <summary>
/// 入隊
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRightPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
}
/// <summary>
/// 出隊
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListRightPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListRightPopAsync(key));
return ConvertObj<T>(value);
}
/// <summary>
/// 入棧
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListLeftPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
}
/// <summary>
/// 出棧
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListLeftPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListLeftPopAsync(key));
return ConvertObj<T>(value);
}
/// <summary>
/// 獲取集合中的數量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.ListLengthAsync(key));
}
#endregion 非同步方法
#endregion List
#region SortedSet 有序集合
#region 同步方法
/// <summary>
/// 新增
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public bool SortedSetAdd<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score));
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public bool SortedSetRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
}
/// <summary>
/// 獲取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> SortedSetRangeByRank<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key);
return ConvetList<T>(values);
});
}
/// <summary>
/// 獲取集合中的數量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetLength(key));
}
#endregion 同步方法
#region 非同步方法
/// <summary>
/// 新增
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score));
}
/// <summary>
/// 刪除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<bool> SortedSetRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
}
/// <summary>
/// 獲取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
return ConvetList<T>(values);
}
/// <summary>
/// 獲取集合中的數量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetLengthAsync(key));
}
#endregion 非同步方法
#endregion SortedSet 有序集合
#region key
/// <summary>
/// 刪除單個key
/// </summary>
/// <param name="key">redis key</param>
/// <returns>是否刪除成功</returns>
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyDelete(key));
}
/// <summary>
/// 刪除多個key
/// </summary>
/// <param name="keys">rediskey</param>
/// <returns>成功刪除的個數</returns>
public long KeyDelete(List<string> keys)
{
List<string> newKeys = keys.Select(AddSysCustomKey).ToList();
return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 判斷key是否儲存
/// </summary>
/// <param name="key">redis key</param>
/// <returns></returns>
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExists(key));
}
/// <summary>
/// 重新命名key
/// </summary>
/// <param name="key">就的redis key</param>
/// <param name="newKey">新的redis key</param>
/// <returns></returns>
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyRename(key, newKey));
}
/// <summary>
/// 設定Key的時間
/// </summary>
/// <param name="key">redis key</param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExpire(key, expiry));
}
#endregion key
#region 釋出訂閱
/// <summary>
/// Redis釋出訂閱 訂閱
/// </summary>
/// <param name="subChannel"></param>
/// <param name="handler"></param>
public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Subscribe(subChannel, (channel, message) =>
{
if (handler == null)
{
Console.WriteLine(subChannel + " 訂閱收到訊息:" + message);
}
else
{
handler(channel, message);
}
});
}
/// <summary>
/// Redis釋出訂閱 釋出
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel"></param>
/// <param name="msg"></param>
/// <returns></returns>
public long Publish<T>(string channel, T msg)
{
ISubscriber sub = _conn.GetSubscriber();
return sub.Publish(channel, ConvertJson(msg));
}
/// <summary>
/// Redis釋出訂閱 取消訂閱
/// </summary>
/// <param name="channel"></param>
public void Unsubscribe(string channel)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Unsubscribe(channel);
}
/// <summary>
/// Redis釋出訂閱 取消全部訂閱
/// </summary>
public void UnsubscribeAll()
{
ISubscriber sub = _conn.GetSubscriber();
sub.UnsubscribeAll();
}
#endregion 釋出訂閱
#region 其他
public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
}
public IDatabase GetDatabase()
{
return _conn.GetDatabase(DbNum);
}
public IServer GetServer(string hostAndPort)
{
return _conn.GetServer(hostAndPort);
}
/// <summary>
/// 設定字首
/// </summary>
/// <param name="customKey"></param>
public void SetSysCustomKey(string customKey)
{
CustomKey = customKey;
}
#endregion 其他
#region 輔助方法
private string AddSysCustomKey(string oldKey)
{
var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
return prefixKey + oldKey;
}
private T Do<T>(Func<IDatabase, T> func)
{
var database = _conn.GetDatabase(DbNum);
return func(database);
}
private string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
}
private T ConvertObj<T>(RedisValue value)
{
return JsonConvert.DeserializeObject<T>(value);
}
private 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;
}
private RedisKey[] ConvertRedisKeys(List<string> redisKeys)
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
}
#endregion 輔助方法
}
}
相關文章
- Spring(3)-AOP快速入手Spring
- 教你如何打好根基快速入手react,vue,nodeReactVue
- <<快速入手Rust>>14.HashMap和其他集合RustHashMap
- Hyperf 如何快速釋放 DB 連線
- Redis 快速上手Redis
- Redis快速入門Redis
- Azure Cosmos DB (五) .Net Core 控制檯應用
- Redis OM .NET Redis物件對映框架Redis物件框架
- Redis在.net中的使用(2).net專案中的Redis使用Redis
- <<快速入手Rust>>1.使用playlaygroud進行簡單快速的線上rust開發Rust
- <<快速入手Rust>>2.使用Clion、IDEA或者Pycharm開發RustRustIdeaPyCharm
- .Net使用Redis詳解之ServiceStack.RedisRedis
- 快速定位 Redis 熱 key?Redis
- 使用Cloud DB構建APP 快速入門 - iOS篇CloudAPPiOS
- 【Redis】redis-cluster到redis-cluster的快速複製Redis
- Redis在.net中的使用(5)Redis持久化Redis持久化
- DB庫伺服器重灌OS的快速恢復配置伺服器
- db如何快速回滾和恢復,DBA的神技能!
- Redis當機 快速恢復Redis
- 如何快速定位 Redis 熱 key?Redis
- Redis在.net中的使用(6)Redis併發鎖Redis
- ASP.NET Core Web API 索引 (更新Redis in .NET Core)ASP.NETWebAPI索引Redis
- 使用redis-trib.rb工具快速搭建redis叢集Redis
- Redis in .NET Core 入門:(3) HashRedis
- Redis in .NET Core 入門:(2) StringRedis
- 5分鐘快速瞭解 RedisRedis
- Spring Boot 如何快速整合 Redis 哨兵?Spring BootRedis
- Redis在.net中的使用(1)下載安裝RedisRedis
- 教你:怎麼快速把電話號碼批量匯入手機通訊錄
- 手遊海外推廣如何贏在起跑線?
- 2020年將是雲遊戲的起跑線?遊戲
- Redis在.net中的使用(7)redis部署為Windows服務RedisWindows
- 快速搞懂.NET 5/.NET Core應用程式的釋出部署
- msyql 同步管道方式快速匯入redisRedis
- LeaRun快速開發平臺,快速開發.net/java專案Java
- Visual Studio 快速分析 .NET Dump 檔案
- ASP.NET CORE[練習22]-Redis6-Microsoft.Extensions.Caching.redisASP.NETRedisROS
- 十六、.net core(.NET 6)搭建基於Redis的Hangfire定時器Redis定時器