Redis 管理分散式緩存

1.配置 Redis 快取

// 1.配置 Redis 快取:

using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

class Program
{
   static async Task Main(string[] args)
   {
        var services = new ServiceCollection();

// 新增服務(伺服器、名稱)

        services.AddStackExchangeRedisCache(options =>
       {
           options.Configuration = “localhost:6379”;
           options.InstanceName = “CacheExample”;
       });
       var provider = services.BuildServiceProvider();
       var cache = provider.GetRequiredService<IDistributedCache>();
       Console.WriteLine(“Redis cache setup complete.”);
   }
}

// 2.新增快取過期策略

var cacheEntryOptions = new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), // 10分鐘後過期
    SlidingExpiration = TimeSpan.FromMinutes(2) // 如果再2分鐘內訪問就重置
};

// 儲存資料到快取
await cache.SetStringAsync(“taskKey”, “Sample Task”, cacheEntryOptions);
Console.WriteLine(“Cache entry set with absolute and sliding expiration.”);

// 檢查快取資料
var cachedValue = await cache.GetStringAsync(“taskKey”);
Console.WriteLine(cachedValue != null ? $”Cache hit: {cachedValue}” : “Cache miss: Value expired.”);

// 3.新增手動刪除快取方法:

async Task InvalidateCache(IDistributedCache cache, string key)
{
    await cache.RemoveAsync(key); // 清除過期快取
   Console.WriteLine($”Cache entry ‘{key}’ has been invalidated.”);
}

// 觸發緩存失效
Console.WriteLine(“Press any key to invalidate cache…”);
Console.ReadKey();

await InvalidateCache(cache, “taskKey”);

// 4.記錄快取

async Task<string> GetCachedData(IDistributedCache cache, string key)
{
   var cachedValue = await cache.GetStringAsync(key);

   if (cachedValue != null)
   {
       Console.WriteLine($”Cache hit: {cachedValue}”);
       return cachedValue;
   }
    Console.WriteLine(“Cache miss: Fetching new data…”);

    var newValue = “Fetched Task Data”;

   await cache.SetStringAsync(key, newValue, new DistributedCacheEntryOptions
   {
       AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
       SlidingExpiration = TimeSpan.FromMinutes(2)
   });
   Console.WriteLine(“New data cached.”);
   return newValue;
}

// 模擬快取訪問
for (int i = 0; i < 5; i++)
{
   await GetCachedData(cache, “taskKey”);
   await Task.Delay(TimeSpan.FromSeconds(10));
}

# 預期控制台輸出
Redis cache setup complete.
Cache entry set with absolute and sliding expiration.
Cache hit: Sample Task
Press any key to invalidate cache…
Cache entry ‘taskKey’ has been invalidated.
Cache miss: Fetching new data…
New data cached.
Cache hit: Fetched Task Data
Cache hit: Fetched Task Data
Cache hit: Fetched Task Data
Cache hit: Fetched Task Data
Cache miss: Fetching new data…
New data cached.

發佈留言