ServiceStack.Redis
初識Redis時接觸到的.Net-Redis組件是 ServiceStack.Redis,其V3系列的最新版本是:ServiceStack.Redis.3.9.29.0。
ServiceStack.Common.dll ServiceStack.Interfaces.dll ServiceStack.Redis.dll ServiceStack.Text.dll
RedisClient
public void Init(); public bool ContainsKey(string key); public bool Remove(string key); public void RemoveByPattern(string pattern); public void RemoveByRegex(string pattern); public IEnumerable<string> GetKeysByPattern(string pattern); public List<string> SearchKeys(string pattern); public List<string> GetAllKeys(); // 數據庫內的所有鍵(慎用) public string GetRandomKey(); public T Get<T>(string key); public IRedisTypedClient<T> As<T>(); // /* 重要 */ public bool Add<T>(string key, T value [, DateTime expiresAt]); // [設置過期時間] public bool Add<T>(string key, T value [, TimeSpan expiresIn]); public bool Set<T>(string key, T value [, DateTime expiresAt]); // [設置過期時間] public bool Set<T>(string key, T value [, TimeSpan expiresIn]); public bool ExpireEntryAt(string key, DateTime expireAt); // 設置過期時間 public bool ExpireEntryIn(string key, TimeSpan expireIn); public TimeSpan GetTimeToLive(string key); // TTL時間 public long DecrementValue(string key); // 減 public long DecrementValueBy(string key, int count); public long IncrementValue(string key); // 增 public long IncrementValueBy(string key, int count);
支持類型
// string public long GetStringCount(string key); public string GetValue(string key); public void SetValue(string key, string value [, TimeSpan expireIn]); public void RenameKey(string fromName, string toName); public int AppendToValue(string key, string value); public string GetAndSetValue(string key, string value); public string GetSubstring(string key, int fromIndex, int toIndex); public List<string> GetValues(List<string> keys); public Dictionary<string, string> GetValuesMap(List<string> keys); // List public int GetListCount(string listId); public int RemoveItemFromList(string listId, string value); public string RemoveStart/End/AllFromList(string listId); public void SetItemInList(string listId, int listIndex, string value); public void AddItemToList(string listId, string value); public void AddRangeToList(string listId, List<string> values); public List<string> GetAllItemsFromList(string listId); public string GetItemFromList(string listId, int listIndex); public List<string> GetRangeFromList(string listId, int startingFrom, int endingAt); public List<string> GetRangeFromSortedList(string listId, int startingFrom, int endingAt); public List<string> GetSortedItemsFromList(string listId, SortOptions sortOptions); public List<T> GetValues<T>(List<string> keys); public Dictionary<string, T> GetValuesMap<T>(List<string> keys); // List作為隊列 public void EnqueueItemOnList(string listId, string value); public string DequeueItemFromList(string listId); // List作為棧 public void PushItemToList(string listId, string value); public string PopItemFromList(string listId); public string PopAndPushItemBetweenLists(string fromListId, string toListId); // Set public int GetSetCount(string setId); public bool SetContainsItem(string setId, string item); public void RemoveItemFromSet(string setId, string item); public void AddItemToSet(string setId, string item); public void AddRangeToSet(string setId, List<string> items); public HashSet<string> GetAllItemsFromSet(string setId); public string GetRandomItemFromSet(string setId); public List<string> GetSortedEntryValues(string setId, int startingFrom, int endingAt); public HashSet<string> GetDifferencesFromSet(string fromSetId, params string[] withSetIds); public HashSet<string> GetIntersectFromSets(params string[] setIds); public HashSet<string> GetUnionFromSets(params string[] setIds); public void StoreDifferencesFromSet(string intoSetId, string fromSetId, params string[] withSetIds); public void StoreIntersectFromSets(string intoSetId, params string[] setIds); public void StoreUnionFromSets(string intoSetId, params string[] setIds); public void MoveBetweenSets(string fromSetId, string toSetId, string item); public string PopItemFromSet(string setId); // Hash public int GetHashCount(string hashId); public bool HashContainsEntry(string hashId, string key); public bool RemoveEntryFromHash(string hashId, string key); public bool SetEntryInHash(string hashId, string key, string value); public List<string> GetHashKeys(string hashId); public List<string> GetHashValues(string hashId); public Dictionary<string, string> GetAllEntriesFromHash(string hashId); public string GetValueFromHash(string hashId, string key); public List<string> GetValuesFromHash(string hashId, params string[] keys); public T GetFromHash<T>(object id); // SortedSet(zset) public int GetSortedSetCount(string setId); public bool SortedSetContainsItem(string setId, string value); public bool RemoveItemFromSortedSet(string setId, string value); public bool AddItemToSortedSet(string setId, string value [, double score]); public bool AddRangeToSortedSet(string setId, List<string> values [, double score]); public List<string> GetRangeFromSortedSet(string setId, int fromRank, int toRank); public IDictionary<string, double> GetRangeWithScoresFromSortedSet(string setId, int fromRank, int toRank); public List<string> GetAllItemsFromSortedSet[Desc](string setId); public IDictionary<string, double> GetAllWithScoresFromSortedSet(string setId);
其中, public IRedisTypedClient<T> As<T>(); 搭配接口 public interface IRedisTypedClient<T> : IEntityStore<T>{} 和 public interface IEntityStore<T>{} 中提供的方法可以完成各種操作。
在V3.0版本的基礎上,其V4.0版本 ServiceStack.Redis-4.0.52 提供了更多的方法:
- Scan方法;
- 獲取設置配置信息;
- 支持Lua腳本;
public RedisText Custom(params object[] cmdWithArgs); // 執行命令 public RedisClient CloneClient(); public string GetClient(); public void SetClient(string name); public void KillClient(string address); public void ChangeDb(long db); public DateTime GetServerTime(); public DateTime ConvertToServerDate(DateTime expiresAt); public List<Dictionary<string, string>> GetClientsInfo(); public string GetConfig(string configItem); public void SetConfig(string configItem, string value); public void SaveConfig(); public void ResetInfoStats();
其中,Custom()方法可以執行絕大多數的Redis命令,ServiceStack.Redis.Commands定義命令,用於Custom()方法的第一個參數:
public static class Commands{ public static readonly byte[] CommandName; }
由於ServiceStack.Redis的V4.0版本淪為商業用途,需充值否則限制:1)數據類型; 2)每小時訪問次數6000
關於破解V4.0版本限制,參見:https://blog.csdn.net/hwt0101/article/details/80545383
雖然ServiceStack.Redis有15%的性能優勢,但還是推薦使用:StackExchange.Redis
StackExchange.Redis
StackExchange.Redis是專為.Net的Redis客戶端API,被StackOverFlow、微軟官方RedisSessionStateProvider也采用StackExchange.Redis實現。Cache組件 | 微軟官方;
RedisHelper.dll StackExchange.Redis.dll
核心:ConnectionMultiplexer類(線程安全),在命名空間StackExchange.Redis中定義,封裝Redis服務的操作細節,該類的實例被整個應用程序域共享和重用
ConnectionMultiplexer redisClient = ConnectionMultiplexer.Connect("localhost"); IDatabase db = redisClient .GetDatabase();
提供一個工具類參考
public class RedisUtils<T> where T : class { private readonly ConnectionMultiplexer redisConnect; private readonly IDatabase db; private readonly JilJsonUtil<T> _jilUtil; public RedisUtils(string connectionString) { _jilUtil = new JilJsonUtil<T>(); redisConnect = ConnectionMultiplexer.Connect(connectionString); redisConnect.PreserveAsyncOrder = false; db = redisConnect.GetDatabase(); } public string GetString(string _key) { return db.StringGet(_key); } public Dictionary<String, T> GetBatch(HashSet<String> keys) { Dictionary<String, T> res = new Dictionary<String, T>(); Dictionary<string, RedisValue> stringPipelineDic= GetStringPipelining(keys); foreach (var key in stringPipelineDic.Keys) { var value = stringPipelineDic[key]; if (!value.IsNullOrEmpty) { res.Add(key, _jilUtil.Deserialize(value)); } } return res; } ///批量查詢 private Dictionary<string, RedisValue> GetStringPipelining(HashSet<String> keys) { Dictionary<string, RedisValue> res = new Dictionary<string, RedisValue>(); Dictionary<string, Task<RedisValue>> tmp = new Dictionary<string, Task<RedisValue>>(); IBatch batch = db.CreateBatch(); foreach (var it in keys) { Task<RedisValue> stringGetAsync = batch.StringGetAsync(it); tmp.Add(it, stringGetAsync); } batch.Execute(); foreach (var it in keys) { Task<RedisValue> stringGetAsync = tmp[it]; if (!stringGetAsync.Result.IsNullOrEmpty) { res.Add(it, stringGetAsync.Result); } } return res; } ///存單個string的最大值是512M public bool SetString(string key, string valStr, int seconds) { return db.StringSet(key, valStr, TimeSpan.FromSeconds(seconds)); } public bool Set(string key, T value, int seconds) { var jsonStr = _jilUtil.Serialize(value); return db.StringSet(key, jsonStr, TimeSpan.FromSeconds(seconds)); } ///PipeLine public void SetBatch(Dictionary<string, T> dic, int seconds) { IBatch ibatch = db.CreateBatch(); foreach (var _key in dic.Keys) { T val = dic[_key]; ibatch.StringSetAsync(_key, _jilUtil.Serialize(val), TimeSpan.FromSeconds(seconds)); } ibatch.Execute(); } }
問題解決
[1]. 連接redis集群報錯:(StackExchange.Redis.dll-v1.2.1)
StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. InternalFailure on PING 在 StackExchange.Redis.ConnectionMultiplexer.ConnectImpl(Func`1 multiplexerFactory, TextWriter log) 在 StackExchange.Redis.ConnectionMultiplexer.Connect(String configuration, TextWriter log)
原因:客戶端dll版本與redis集群不兼容,替換為 v1.2.6 即可
管道(PipeLine)/批量(Batch)
- 命令打包,降低通信往返時延
StackExchange.Redis兩個神器:ConnectionCounters 和 IProfiler
- ConnectionCounters:分析線程瞬時狀態
- IProfiler:跟蹤一個請求總共執行redis命令及執行時長
對StackExchange.Redis的封裝,參見:
但是,V1.0版本存在 timeout的問題,超時和異步慢的問題初探解決方法:
// 解決超時 ThreadPool.SetMinThreads(xx, xx); // 解決異步慢 connection.PreserveAsyncOrder = false;
該問題在 StackExchange.Redis 2.0 中已解決,重構了異步隊列,采用管道方式解決了異步慢的問題,參見:https://www.cnblogs.com/qhca/p/9347604.html
在 StackExchange.Redis二次封裝 中,建議不要用lock作為單例使用,避免出現超時問題,待驗證....
應用
Log4net+redis日志隊列:https://www.cnblogs.com/dissun/p/10558817.html
Redis監控:由 Opserver工具 ==> RedisMonitor
基於 Redis的 Session共享
環境配置
.NET Framework 4.5 (推薦配置) Microsoft.Web.RedisSessionStateProvider V2.2.6 StackExchange.Redis.StrongName V1.2.1 .NET Framework 4.6.1 RedisSessionProvider V1.2.8 StackExchange.Redis V2.0.6(貌似會報錯,提示用低版本V1.2.6)
使用方法
public static void RegistRedis() { StackExchange.Redis.ConfigurationOptions redisConfigOpts = StackExchange.Redis.ConfigurationOptions.Parse("127.0.0.1:6379"); redisConfigOpts.Password = "********"; RedisSessionProvider.Config.RedisConnectionConfig.GetSERedisServerConfig = (context) => { return new KeyValuePair<string, StackExchange.Redis.ConfigurationOptions>( "DefaultConnection", redisConfigOpts); }; RedisSessionProvider.Config.RedisSessionConfig.SessionTimeout = TimeSpan.MaxValue; }
CsRedis.Core
CsRedis 開源地址參見:https://github.com/2881099/csredis
/// .NET Framework 4.6 /// NuGet.Tools.vsix V2.12 /// CSRdeis.Core V3.0.62
CsRedis引入:https://www.cnblogs.com/kellynic/p/9803314.html