Asp.Net Core 2.0 項目實戰(6)Redis配置、封裝幫助類RedisHelper及使用實例

本文目錄
1. 摘要
2. Redis配置
3. RedisHelper
4.使用實例 5. 總結

1.  摘要

  因爲內存存取速度遠高於磁盤讀取的特性,爲了程序效率提升性能,一般會把經常使用的不常變更的數據存儲在系統內存中,提高數據讀取的速度,在C#下常見的內存操做有微軟自帶的內存處理、分佈式緩存Memcached以及Redis,這裏咱們介紹Redis分佈式緩存,另外兩種緩存處理參考《Asp.Net Core 2.0 項目實戰(8)Core下緩存操做、序列化操做、JSON操做等Helper集合類》介紹了基於Microsoft.Extensions.Caching.Memory封裝CacheHelper緩存幫助類;《Asp.Net Core 2.0 項目實戰(5)Memcached踩坑,基於EnyimMemcachedCore整理MemcachedHelper幫助類。》Memcached幫助類。

2.  Redis配置

  在appsettings.json添加相關配置,配置讀寫redis服務器,多服務器用逗號隔開。

//redis分佈式緩存
  "RedisConfig": { //是否打開緩存1是0否
    "IsOpenCache": "0", "ReadWriteHosts": "192.168.1.2:6379,192.168.1.3:6379,password=123456", "ReadOnlyHosts": "192.168.1.2:6379,password=123456" }

3.  RedisHelper

  添加Nuget包StackExchange.Redis和Newtonsoft.Json;設置Key/Value,刪除redis緩存。本幫助類我僅本地兩臺電腦測試過,生產環境暫未使用,現僅供參考。

using System; using System.Collections.Generic; using Microsoft.Extensions.Logging; using StackExchange.Redis; using Newtonsoft.Json; namespace NC.Common { public class RedisHelper { //單例模式
        public static RedisCommon Default{get { return new RedisCommon(); } } public static RedisCommon One { get { return new RedisCommon(1, "127.0.0.1:6379"); } } public static RedisCommon Two { get { return new RedisCommon(2, "127.0.0.1:6379"); } } } /// <summary>
    /// Redis操做類 /// 老版用的是ServiceStack.Redis。 /// Net Core使用StackExchange.Redis的nuget包 /// </summary>
    public class RedisCommon { public static ILogger Log = UtilLogger<RedisCommon>.Log;//日誌記錄 //redis數據庫鏈接字符串
        private string _conn = UtilConf.Configuration["RedisConfig:ReadWriteHosts"] ?? "127.0.0.1:6379"; private int _db = 0; //靜態變量 保證各模塊使用的是不一樣實例的相同連接
        private static ConnectionMultiplexer connection; public RedisCommon() { } /// <summary>
        /// 構造函數 /// </summary>
        /// <param name="db"></param>
        /// <param name="connectStr"></param>
        public RedisCommon(int db, string connectStr) { _conn = connectStr; _db = db; } /// <summary>
        /// 緩存數據庫,數據庫鏈接 /// </summary>
        public ConnectionMultiplexer CacheConnection { get { try { if (connection == null || !connection.IsConnected) { connection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(_conn)).Value; } } catch (Exception ex) { Log.LogError("RedisHelper->CacheConnection 出錯\r\n" + ex.ToString()); return null; } return connection; } } /// <summary>
        /// 緩存數據庫 /// </summary>
        public IDatabase CacheRedis => CacheConnection.GetDatabase(_db); #region --KEY/VALUE存取--
        /// <summary>
        /// 單條存值 /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">The value.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool StringSet(string key, string value) { return CacheRedis.StringSet(key, value); } /// <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?)) { return CacheRedis.StringSet(key, value, expiry); } /// <summary>
        /// 保存多個key value /// </summary>
        /// <param name="arr">key</param>
        /// <returns></returns>
        public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] arr) { return CacheRedis.StringSet(arr); } /// <summary>
        /// 批量存值 /// </summary>
        /// <param name="keysStr">key</param>
        /// <param name="valuesStr">The value.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool StringSetMany(string[] keysStr, string[] valuesStr) { var count = keysStr.Length; var keyValuePair = new KeyValuePair<RedisKey, RedisValue>[count]; for (int i = 0; i < count; i++) { keyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(keysStr[i], valuesStr[i]); } return CacheRedis.StringSet(keyValuePair); } /// <summary>
        /// 保存一個對象 /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SetStringKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?)) { string json = JsonConvert.SerializeObject(obj); return CacheRedis.StringSet(key, json, expiry); } /// <summary>
        /// 追加值 /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void StringAppend(string key, string value) { ////追加值,返回追加後長度
            long appendlong = CacheRedis.StringAppend(key, value); } /// <summary>
        /// 獲取單個key的值 /// </summary>
        /// <param name="key">Redis Key</param>
        /// <returns></returns>
        public RedisValue GetStringKey(string key) { return CacheRedis.StringGet(key); } /// <summary>
        /// 根據Key獲取值 /// </summary>
        /// <param name="key">鍵值</param>
        /// <returns>System.String.</returns>
        public string StringGet(string key) { try { return CacheRedis.StringGet(key); } catch (Exception ex) { Log.LogError("RedisHelper->StringGet 出錯\r\n" + ex.ToString()); return null; } } /// <summary>
        /// 獲取多個Key /// </summary>
        /// <param name="listKey">Redis Key集合</param>
        /// <returns></returns>
        public RedisValue[] GetStringKey(List<RedisKey> listKey) { return CacheRedis.StringGet(listKey.ToArray()); } /// <summary>
        /// 批量獲取值 /// </summary>
        public string[] StringGetMany(string[] keyStrs) { var count = keyStrs.Length; var keys = new RedisKey[count]; var addrs = new string[count]; for (var i = 0; i < count; i++) { keys[i] = keyStrs[i]; } try { var values = CacheRedis.StringGet(keys); for (var i = 0; i < values.Length; i++) { addrs[i] = values[i]; } return addrs; } catch (Exception ex) { Log.LogError("RedisHelper->StringGetMany 出錯\r\n" + ex.ToString()); return null; } } /// <summary>
        /// 獲取一個key的對象 /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetStringKey<T>(string key) { return JsonConvert.DeserializeObject<T>(CacheRedis.StringGet(key)); } #endregion

        #region --刪除設置過時--
        /// <summary>
        /// 刪除單個key /// </summary>
        /// <param name="key">redis key</param>
        /// <returns>是否刪除成功</returns>
        public bool KeyDelete(string key) { return CacheRedis.KeyDelete(key); } /// <summary>
        /// 刪除多個key /// </summary>
        /// <param name="keys">rediskey</param>
        /// <returns>成功刪除的個數</returns>
        public long KeyDelete(RedisKey[] keys) { return CacheRedis.KeyDelete(keys); } /// <summary>
        /// 判斷key是否存儲 /// </summary>
        /// <param name="key">redis key</param>
        /// <returns></returns>
        public bool KeyExists(string key) { return CacheRedis.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) { return CacheRedis.KeyRename(key, newKey); } /// <summary>
        /// 刪除hasekey /// </summary>
        /// <param name="key"></param>
        /// <param name="hashField"></param>
        /// <returns></returns>
        public bool HaseDelete(RedisKey key, RedisValue hashField) { return CacheRedis.HashDelete(key, hashField); } /// <summary>
        /// 移除hash中的某值 /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="dataKey"></param>
        /// <returns></returns>
        public bool HashRemove(string key, string dataKey) { return CacheRedis.HashDelete(key, dataKey); } /// <summary>
        /// 設置緩存過時 /// </summary>
        /// <param name="key"></param>
        /// <param name="datetime"></param>
        public void SetExpire(string key, DateTime datetime) { CacheRedis.KeyExpire(key, datetime); } #endregion } }

 

4.  使用實例

  在HomeCtroller控制器中添加測試redis方法以下:寫;讀;刪除。

public IActionResult Index() { #region --測試redis-- RedisHelper.Default.StringSet("redis", "redis" + DateTime.Now, TimeSpan.FromSeconds(1000000)); ViewData["redis"] = RedisHelper.Default.StringGet("redis"); //RedisHelper.Default.KeyDelete("redis");
            #endregion
            return View(); } 

5.  總結

  Redis讀寫速度快性能高,但部署到生產環境中要注意端口、密碼設置,最好是部署在內網環境中,另因爲以前都是使用ServiceStack.Redis,因爲ServiceStack.Redis v4版本後是收費版的,好像還有每小時6000次訪問請求的問題需注意,具體這倆請自行搜索對比。Redis 有五種經常使用數據類型,字符串類型(string),散列類型(hash),列表類型(list),集合類型(set),有序集合類型(zset)參考:http://www.javashuo.com/article/p-fjtlfdty-kr.html;這裏我暫只處理了string類型,上面我測試的方法有限,其餘類型各位可自行補充,網上有不少案例。

相關文章
相關標籤/搜索