diff --git a/docs/zh-Hans/Caching.md b/docs/zh-Hans/Caching.md index 0939947d87..7379104f51 100644 --- a/docs/zh-Hans/Caching.md +++ b/docs/zh-Hans/Caching.md @@ -80,6 +80,92 @@ public class BookService : ITransientDependency `IDistributedCache` 的其他方法与ASP.NET Core的`IDistributedCache` 接口相同, 你可以参考 [ASP.NET Core文档](https://docs.microsoft.com/zh-cn/aspnet/core/performance/caching/distributed). +## `IDistributedCache` 接口 + +`IDistributedCache` 接口默认了键是 `string` 类型 (如果你的键不是string类型需要进行手动类型转换). `IDistributedCache` 将键的类型泛型化试图简化手动转换的操作. + +### 使用示例 + +示例缓存项 + +````csharp +public class BookCacheItem +{ + public string Name { get; set; } + + public float Price { get; set; } +} +```` + +用法示例 (这里假设你的键类型是 `Guid`): + +````csharp +public class BookService : ITransientDependency +{ + private readonly IDistributedCache _cache; + + public BookService(IDistributedCache cache) + { + _cache = cache; + } + + public async Task GetAsync(Guid bookId) + { + return await _cache.GetOrAddAsync( + bookId, //Guid type used as the cache key + async () => await GetBookFromDatabaseAsync(bookId), + () => new DistributedCacheEntryOptions + { + AbsoluteExpiration = DateTimeOffset.Now.AddHours(1) + } + ); + } + private Task GetBookFromDatabaseAsync(Guid bookId) + { + //TODO: get from database + } +} +```` + +* 示例服务中 `GetOrAddAsync()` 方法获取缓存的图书项. +* 我们采用了 `Guid` 做为键,在 `_cache_GetOrAddAsync()` 方法中传入 `Guid` 类型的bookid. + +`IDistributedCache` 在内部使用键对象的 `ToString()` 方法转换类型为string. 如果你的将复杂对象做为键,那么需要重写类的 `ToString` 方法. + +示例: + +````csharp +public class UserInOrganizationCacheKey +{ + public Guid UserId { get; set; } + + public Guid OrganizationId { get; set; } + + //构建缓存key + public override string ToString() + { + return $"{UserId}_{OrganizationId}"; + } +} +```` + +用法示例: + +````csharp +public class BookService : ITransientDependency +{ + private readonly IDistributedCache _cache; + + public BookService( + IDistributedCache cache) + { + _cache = cache; + } + + ... +} +```` + ### DistributedCacheOptions TODO \ No newline at end of file