分散式快取NCache使用

abstractcyj發表於2022-02-28

NCache作為快取優點幣Redis有優勢,但是收費的所以選用的不多吧。下面簡單實操一下:

首先官網下載元件NCache Download Center (alachisoft.com),這裡選擇企業和專業版都可以,都只有一個月試用期,下一步後統一協議,後彈出第二個介面需要填寫一下注冊資訊。重點是workemail,這裡需要工作郵箱,字尾是qq,163的都不行。我用的是zoho的郵箱。

 

下載完畢後需要通過cmd管理員命令去安裝msi的檔案,因為msi不能通過右鍵管理員來執行,二這個必須要管理員許可權(有疑問 搜尋管理員身份執行msi安裝),安裝過程中需要安裝key,註冊的郵箱裡面有這個。

安裝完後會有這幾個出現在開始選單,只需要開啟NCache Web Manager,可以開啟localhost:8251的管理介面。Cache Name和Servers需要在程式碼和配置檔案中做好配置。

 

 

下面新建netcore6 webapi程式,匯入NCache的包會自動生成:client.ncconf和config.ncconf兩個配置檔案,重點修改client.ncconf檔案的兩處服務ip,還有程式碼

configuration.CacheName = "ClusteredCache"; 指定CacheName名稱為上圖的Cache Name。

using Alachisoft.NCache.Caching.Distributed;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.SqlServer;
using Microsoft.Extensions.Caching.StackExchangeRedis;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();

builder.Services.AddNCacheDistributedCache(configuration =>
{
    configuration.CacheName = "ClusteredCache";
    configuration.EnableLogs = true;
    configuration.ExceptionsEnabled = true;
});

var app = builder.Build();

#region snippet_Configure
app.Lifetime.ApplicationStarted.Register(() =>
{
    var currentTimeUTC = DateTime.UtcNow.ToString();
    byte[] encodedCurrentTimeUTC = System.Text.Encoding.UTF8.GetBytes(currentTimeUTC);
    var options = new DistributedCacheEntryOptions()
        .SetSlidingExpiration(TimeSpan.FromSeconds(20));
    app.Services.GetService<IDistributedCache>()
                              .Set("cachedTimeUTC", encodedCurrentTimeUTC, options);
});
#endregion

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Distributed;
using System.Text;

namespace SampleApp.Pages
{
    #region snippet_IndexModel
    public class IndexModel : PageModel
    {
        private readonly IDistributedCache _cache;

        public IndexModel(IDistributedCache cache)
        {
            _cache = cache;
        }

        public string? CachedTimeUTC { get; set; }
        public string? ASP_Environment { get; set; }

        public async Task OnGetAsync()
        {
            CachedTimeUTC = "Cached Time Expired";
            var encodedCachedTimeUTC = await _cache.GetAsync("cachedTimeUTC");

            if (encodedCachedTimeUTC != null)
            {
                CachedTimeUTC = Encoding.UTF8.GetString(encodedCachedTimeUTC);
            }

            ASP_Environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            if (String.IsNullOrEmpty(ASP_Environment))
            {
                ASP_Environment = "Null, so Production";
            }
        }

        public async Task<IActionResult> OnPostResetCachedTime()
        {
            var currentTimeUTC = DateTime.UtcNow.ToString();
            byte[] encodedCurrentTimeUTC = Encoding.UTF8.GetBytes(currentTimeUTC);
            var options = new DistributedCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromSeconds(20));
            await _cache.SetAsync("cachedTimeUTC", encodedCurrentTimeUTC, options);

            return RedirectToPage();
        }
    }
    #endregion
}

執行效果圖如下:

示例程式碼:

exercise/NCacheDistCache at master · liuzhixin405/exercise (github.com)

參考來源:

ASP.NET Core 中的分散式快取 | Microsoft Docs

相關文章