You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.8 KiB
60 lines
1.8 KiB
using CSRedis;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.Caching.Redis;
|
|
using System.Security.AccessControl;
|
|
|
|
|
|
namespace SBF.API.Extentions
|
|
{
|
|
public static class HostExtentions
|
|
{
|
|
/// <summary>
|
|
/// 使用缓存
|
|
/// </summary>
|
|
/// <param name="hostBuilder">建造者</param>
|
|
/// <returns></returns>
|
|
public static IHostBuilder UseCache(this IHostBuilder hostBuilder)
|
|
{
|
|
|
|
|
|
hostBuilder.ConfigureServices((buidlerContext, services) =>
|
|
{
|
|
var cacheOption = buidlerContext.Configuration.GetSection("Cache").Get<CacheOptions>();
|
|
switch (cacheOption.CacheType)
|
|
{
|
|
case CacheType.Memory: services.AddDistributedMemoryCache(); break;
|
|
case CacheType.Redis:
|
|
{
|
|
var csredis = new CSRedisClient(cacheOption.RedisEndpoint);
|
|
RedisHelper.Initialization(csredis);
|
|
services.AddSingleton(csredis);
|
|
services.AddSingleton<IDistributedCache>(new CSRedisCache(RedisHelper.Instance));
|
|
}; break;
|
|
default: throw new Exception("缓存类型无效");
|
|
}
|
|
});
|
|
|
|
return hostBuilder;
|
|
}
|
|
|
|
}
|
|
internal class CacheOptions
|
|
{
|
|
public CacheType CacheType { get; set; }
|
|
public string RedisEndpoint { get; set; }
|
|
} /// <summary>
|
|
/// 缓存类型
|
|
/// </summary>
|
|
public enum CacheType
|
|
{
|
|
/// <summary>
|
|
/// 使用内存缓存(不支持分布式)
|
|
/// </summary>
|
|
Memory,
|
|
|
|
/// <summary>
|
|
/// 使用Redis缓存(支持分布式)
|
|
/// </summary>
|
|
Redis
|
|
}
|
|
}
|
|
|