asp.net core上使用Redis探索(2)

来源:https://www.cnblogs.com/zhiyong-ITNote/archive/2018/04/25/8944200.html
-Advertisement-
Play Games

在<<asp.net core上使用Redis探索(1)>>中,我介紹了一個微軟官方實現Microsoft.Extensions.Caching.Redis的類庫,這次,我們使用微軟官方的Redis客戶端。 使用Nuget引入Microsoft.Extensions.Caching.Redis庫, ...


在<<asp.net core上使用Redis探索(1)>>中,我介紹了一個微軟官方實現Microsoft.Extensions.Caching.Redis的類庫,這次,我們使用微軟官方的Redis客戶端。

使用Nuget引入Microsoft.Extensions.Caching.Redis庫, 依賴項:
Microsoft.Extensions.Caching.Abstract
Microsoft.Extensions.Options
StackExchange.Redis.StrongName

原來Microsoft.Extensions.Caching.Redis其實就是封裝了StackExchange.redis,作為.net core平臺下的redis客戶端與redis通信的。


源碼地址:
https://github.com/aspnet/Caching/tree/dev/src/Microsoft.Extensions.Caching.Redis
源碼分析:
RedisCache繼承自IDistributeCache介面,該介面是Microsoft.Extensions.Caching.Distributed命名空間下的一個介面,主要就是封裝了Redis的一些最基本的操作,比如,Set, Get, Refresh, Remove.就是最基本的增刪改查。
RedisCache類中有一個用於同步的SemaphoreSlim類,該類是CLR中的同步遍歷的混合構造——內核模式和用戶模式的混合。該類除了顯式實現了IDistributedCache的所有方法外,還有一個重要的方法要說下,那就是Connect()方法:

 1 private void Connect()
 2 {
 3     if (_cache != null)
 4     {
 5         return;
 6     }
 7 
 8     _connectionLock.Wait();
 9     try
10     {
11         if (_cache == null)
12         {
13             _connection = ConnectionMultiplexer.Connect(_options.Configuration);
14             _cache = _connection.GetDatabase();
15         }
16     }
17     finally
18     {
19         _connectionLock.Release();
20     }
21 }

該方法用於連接Redis伺服器,通過RedisCacheOptions這個類的屬性,來連接redis資料庫,源碼:

 1 /// <summary>
 2 /// Configuration options for <see cref="RedisCache"/>.
 3 /// </summary>
 4 public class RedisCacheOptions : IOptions<RedisCacheOptions>
 5 {
 6     /// <summary>
 7     /// The configuration used to connect to Redis.
 8     /// </summary>
 9     public string Configuration { get; set; }
10 
11     /// <summary>
12     /// The Redis instance name.
13     /// </summary>
14     public string InstanceName { get; set; }
15 
16     RedisCacheOptions IOptions<RedisCacheOptions>.Value
17     {
18         get { return this; }
19     }
20 }

其中的Configuration屬性就是我們的一般在.config文件中配置redis連接語句的地方,隨後我們會講到應用。而InstanceName是什麼?繼續看源碼(RedisCache.cs文件):

private readonly RedisCacheOptions _options;
public RedisCache(IOptions<RedisCacheOptions> optionsAccessor)
{
    if (optionsAccessor == null)
    {
        throw new ArgumentNullException(nameof(optionsAccessor));
    }

    _options = optionsAccessor.Value;

    // This allows partitioning a single backend cache for use with multiple apps/services.
    _instance = _options.InstanceName ?? string.Empty;
}

可以看到,這個屬性是可以設置為空的,那麼它到底是什麼呢?這個就是我們在存儲redis的時候的首碼了,我們可以這麼這是Demo, 或者Demo:test等。
也就是說RedisCache類主要就是實現了IDistributedCache介面的所有方法,同時另外實現了Connect()方法用來連接redis,而這個的連接又是基於StackExchange.Redis(關於StackExchange.Redis請看  StackExchange.Redis通用封裝類分享 )的ConnectionMultiplexer。但是我們在大型項目中使用的redis隊列在RedisCache類中並沒有實現,但是,要知道整個asp.net-core都是可拓展的,我們可以基於RedisCache類再實現一個pub/sub方法用來做消息隊列。
最後使用asp.net-core預設的DI容器將RedisCache類註冊到框架中。RedisCacheServiceCollectionExtensions類源碼:

 1 /// <summary>
 2 /// Extension methods for setting up Redis distributed cache related services in an <see cref="IServiceCollection" />.
 3 /// </summary>
 4 public static class RedisCacheServiceCollectionExtensions
 5 {
 6     /// <summary>
 7     /// Adds Redis distributed caching services to the specified <see cref="IServiceCollection" />.
 8     /// </summary>
 9     /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
10     /// <param name="setupAction">An <see cref="Action{RedisCacheOptions}"/> to configure the provided
11     /// <see cref="RedisCacheOptions"/>.</param>
12     /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
13     public static IServiceCollection AddDistributedRedisCache(this IServiceCollection services, Action<RedisCacheOptions> setupAction)
14     {
15         if (services == null)
16         {
17             throw new ArgumentNullException(nameof(services));
18         }
19 
20         if (setupAction == null)
21         {
22             throw new ArgumentNullException(nameof(setupAction));
23         }
24 
25         services.AddOptions();
26         services.Configure(setupAction);
27         // .net core DI容器的使用無非就是在容器中實例化介面,而介面的的實例化,是通過實例化介面的派生類(即以介面為父類的子類)...
28         services.Add(ServiceDescriptor.Singleton<IDistributedCache, RedisCache>());
29 
30         return services;
31     }
32 }

在這裡我們基於IServiceCollection介面拓展出來了一個方法,該方法就是微軟官方為我們創建的基於Redis的實現了,在最後使用DI的三種方法的Singleton來實現IOC。那麼我們怎麼來使用呢?
引入完了Microsoft.Extensions.Caching.Redis之後,在Startup類中:

1 services.AddDistributedRedisCache(option =>
2 {
3     option.Configuration = "123.207.96.138:6379, password=*****";
4     option.InstanceName = "";
5 });

個人的建議是給Redis設置一個密碼,要不然容易被攻擊。
接下來就是給Redis設置值了, 我們新建一個WebApi的程式,然後新建一個HomeController Api控制器

 1 [Produces("application/json")]
 2 [Route("api/[controller]")]
 3 public class HomeController : Controller
 4 {
 5     // 通過構造函數註入,內置IOC容器實例化了之後,就可以通過介面對象來調用相應的函數了.
 6     private readonly IDistributedCache _distributedCache;
 7 
 8     public HomeController(IDistributedCache distributedCache)
 9     {
10         _distributedCache = distributedCache;
11     }
12 
13     [HttpGet]
14     public async Task<string> Get()
15     {
16         
17         var cacheKey = "TheTime";
18 
19         //await _distributedCache.RemoveAsync(cacheKey);
20         
21         var existingTime = _distributedCache.GetString(cacheKey);
22         if (!string.IsNullOrEmpty(existingTime))
23         {
24             return "Fetched from cache : " + existingTime;
25         }
26         else
27         {
28             existingTime = DateTime.UtcNow.ToString();
29             
30             _distributedCache.SetString(cacheKey, existingTime);
31             return "Added to cache : " + existingTime;
32         }
33     }
34 }

代碼我就不運行了,親測能用。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. 如何查看一個類及其父類中的所有方法和屬性 答: Ctrl + o 後,顯示當前類的欄位和方法;再按一次,同時顯示父類的欄位和方法,藍色字為父類屬性 ...
  • 恢復內容開始 去年在網路上有一篇文章特別有名:我分析42萬字的歌詞,為搞清楚民謠歌手們在唱些什麼。這篇文章的作者是我大學的室友,隨後網路上出現了各種以為爬取了XXX,發現了XXX為名的文章。我想了想,我能不能也通過爬蟲來做些什麼呢?先入為主,我也以歌曲作為切入口 周傑倫,是的,我們這一代的生活成長, ...
  • 1 #coding=utf-8 2 #Version:python 3.6.0 3 #Tools:Pycharm 2017.3.2 4 _date_ = '2018/4/25/025 21:02' 5 6 class school(object): 7 def __init__(self,name, ...
  • Python函數式編程 函數式編程可以使代碼更加簡潔,易於理解。Python提供的常見函數式編程方法如下: map(函數,可迭代式) 映射函數 filter(函數,可迭代式) 過濾函數 reduce(函數,可迭代式) 規約函數 lambda 函數 列表推導式 zip()函數 1列表推導式 [1, 2 ...
  • 參考資料: .NET Reflector反編譯項目如何修複 https://jingyan.baidu.com/article/e4511cf33777862b855eaf6d.html 批量修複資源文件程式源碼:https://download.csdn.net/download/kingdom1 ...
  • 本文基於GitHub演示自動化部署,實際上你可以選擇任意的Git托管環境。 使用的模式:DooD(Docker outside of Docker)。 本文所有內容均開源 鏈接 歡迎關註我的GitHub: "neverc/netcore jenkins" (由於是半年前構建的,sdk版本為dotne ...
  • 1、左連接: var LeftJoin = from emp in ListOfEmployeesjoin dept in ListOfDepartmenton emp.DeptID equals dept.ID into JoinedEmpDeptfrom dept in JoinedEmpDep ...
  • 上篇 net 同步非同步 中篇 多線程的使用(Thread) 下篇 net 任務工廠實現非同步多線程 Thread多線程概述 Thread多線程概述 上一篇我們介紹了net 的同步與非同步,我們非同步演示的時候使用的是委托多線程來實現的。今天我們來細細的剖析下 多線程。 多線程的優點:可以同時完成多個任務; ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...