> For the complete documentation index, see [llms.txt](https://monksoul.gitbook.io/hoa/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monksoul.gitbook.io/hoa/huancunguanli.md).

# 十六、缓存管理

## 缓存的概念

所谓的缓存，就是将程序或系统经常要调用的对象存在内存中，使其使用时可以快速调用，不必再去创建新的重复的实例。这样做可以减少系统开销，提高系统效率。

## 缓存类型

* `通过文件缓存`：顾名思义文件缓存是指把数据存储在磁盘上，不管你是以XML格式，序列化文件DAT格式还是其它文件格式
* `内存缓存`：也就是创建一个静态内存区域，将数据存储进去，例如我们B/S架构的将数据存储在Application中或者存储在一个静态Map中
* `本地内存缓存`：就是把数据缓存在本机的内存中
* `分布式缓存机制`：可能存在跨进程，跨域访问缓存数据。对于分布式的缓存，此时因为缓存的数据是放在缓存服务器中的，或者说，此时应用程序需要跨进程的去访问分布式缓存服务器。

## 缓存的使用

### 内存中的缓存

Hoa Framework 框架中已经默认注入了内存缓存的服务，可以在构造函数中注入使用：

```csharp
public class HomeController : Controller
{
    private IMemoryCache _cache;

    public HomeController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }
}
```

更多内存中的缓存[可查看官方文档](https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/memory?view=aspnetcore-3.1)。

### 分布式缓存

分布式缓存通常由两种，一种是不跨服务器但跨应用的缓存，另外一种是跨服务器的缓存。前者一般简称**分布式内存缓存**，后者统称是**分布式缓存**。

#### :flag\_black: 示例一，使用分布式内存缓存

若要使用分布式内存缓存，需要在 `Hoa.Web.Core.ServiceExtensions.HoaCacheConfigureExtension.cs` 文件中配置并启用：

```csharp
using Microsoft.Extensions.DependencyInjection;

namespace Hoa.Web.Core.ServiceExtensions
{
    public static class HoaCacheConfigureExtension
    {
        public static IServiceCollection AddCacheConfigure(this IServiceCollection services)
        {
            // 启用分布式内存缓存
            services.AddDistributedMemoryCache();
            
            // 启用 Redis缓存，需要安装Redis服务。
            if (AppGlobal.AppConfigOptions.EnableRedisCache)
            {
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = "localhost";
                    options.InstanceName = "Hoa_";
                });
            }

            return services;
        }
    }
}
```

在代码中使用

```csharp
public class IndexModel : PageModel
{
    private readonly IDistributedCache _cache;

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

    public string CachedTimeUTC { get; set; }

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

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

    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();
    }
}
```

更多分布式缓存[可查看官方文档](https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed?view=aspnetcore-3.1)。
