79 lines
2.2 KiB
C#
79 lines
2.2 KiB
C#
|
|
using Microsoft.Extensions.Configuration;
|
|||
|
|
using Microsoft.Identity.Client;
|
|||
|
|
using NewLife.Caching.Services;
|
|||
|
|
using NewLife.Caching;
|
|||
|
|
using NewLife.Log;
|
|||
|
|
using SqlSugar;
|
|||
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Text;
|
|||
|
|
using System.Threading.Tasks;
|
|||
|
|
using YY.Admin.Core;
|
|||
|
|
using YY.Admin.Core.Option;
|
|||
|
|
using NewLife.Configuration;
|
|||
|
|
|
|||
|
|
public static class CacheExtensions
|
|||
|
|
{
|
|||
|
|
/// <summary>
|
|||
|
|
/// 注册缓存服务
|
|||
|
|
/// </summary>
|
|||
|
|
public static void AddNewLifeCache(this IContainerRegistry containerRegistry,IConfiguration configuration)
|
|||
|
|
{
|
|||
|
|
// 读取配置
|
|||
|
|
var BaseCacheOptions = configuration.GetSection("Cache").Get<BaseCacheOptions>();
|
|||
|
|
|
|||
|
|
// 注册配置选项
|
|||
|
|
containerRegistry.RegisterInstance(BaseCacheOptions);
|
|||
|
|
|
|||
|
|
// 注册缓存提供器
|
|||
|
|
if (BaseCacheOptions.CacheType == CacheTypeEnum.Redis.ToString())
|
|||
|
|
{
|
|||
|
|
containerRegistry.RegisterSingleton<ICacheProvider>(() =>
|
|||
|
|
{
|
|||
|
|
return CreateRedisCacheProvider(BaseCacheOptions);
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
// 默认使用内存缓存
|
|||
|
|
containerRegistry.RegisterSingleton<ICacheProvider, CacheProvider>();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 注册缓存服务
|
|||
|
|
containerRegistry.RegisterSingleton<ISysCacheService, SysCacheService>();
|
|||
|
|
}
|
|||
|
|
private static ICacheProvider CreateRedisCacheProvider(BaseCacheOptions options)
|
|||
|
|
{
|
|||
|
|
var redis = new FullRedis
|
|||
|
|
{
|
|||
|
|
Name = "RedisCache",
|
|||
|
|
Tracer = null, // 禁用跟踪器
|
|||
|
|
Log = XTrace.Log // 使用NewLife日志
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 初始化Redis
|
|||
|
|
redis.Init(options.Redis.Configuration!);
|
|||
|
|
|
|||
|
|
// 设置前缀
|
|||
|
|
if (!string.IsNullOrEmpty(options.Redis.Prefix))
|
|||
|
|
{
|
|||
|
|
redis.Prefix = options.Redis.Prefix;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 设置最大消息大小
|
|||
|
|
if (options.Redis.MaxMessageSize > 0)
|
|||
|
|
{
|
|||
|
|
redis.MaxMessageSize = options.Redis.MaxMessageSize;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
//// 测试连接
|
|||
|
|
//if (!redis.Ping())
|
|||
|
|
//{
|
|||
|
|
// throw new Exception("Redis连接失败,请检查配置");
|
|||
|
|
//}
|
|||
|
|
|
|||
|
|
return new RedisCacheProvider { Cache = redis };
|
|||
|
|
}
|
|||
|
|
}
|