You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
2.5 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System.Threading.Tasks;
using EntrustSettle.Common;
using EntrustSettle.Common.Caches;
using EntrustSettle.Common.Option;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
namespace EntrustSettle.Extensions.ServiceExtensions;
public static class CacheSetup
{
/// <summary>
/// 统一注册缓存
/// </summary>
/// <param name="services"></param>
public static void AddCacheSetup(this IServiceCollection services)
{
//string path = "D:\\EntrustSettle\\委托结算临时日志.txt";s
var cacheOptions = App.GetOptions<RedisOptions>();
cacheOptions.Enabled = AppSettings.app("Redis", "Enabled").ObjToBool();
cacheOptions.ConnectionString = AppSettings.app("Redis", "ConnectionString");
cacheOptions.InstanceName = AppSettings.app("Redis", "InstanceName");
//File.AppendAllText(path, cacheOptions.ToJson() + Environment.NewLine);
if (cacheOptions.Enabled)
{
//File.AppendAllText(path, "添加Redis缓存" + Environment.NewLine);
// 配置启动Redis服务虽然可能影响项目启动速度但是不能在运行的时候报错所以是合理的
services.AddSingleton<IConnectionMultiplexer>(sp =>
{
//获取连接字符串
var configuration = ConfigurationOptions.Parse(cacheOptions.ConnectionString, true);
configuration.ResolveDns = true;
return ConnectionMultiplexer.Connect(configuration);
});
services.AddSingleton<ConnectionMultiplexer>(p => p.GetService<IConnectionMultiplexer>() as ConnectionMultiplexer);
//使用Redis
services.AddStackExchangeRedisCache(options =>
{
options.ConnectionMultiplexerFactory = () => Task.FromResult(App.GetService<IConnectionMultiplexer>(false));
if (!cacheOptions.InstanceName.IsNullOrEmpty()) options.InstanceName = cacheOptions.InstanceName;
});
services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();
}
else
{
//File.AppendAllText(path, "添加内存缓存" + Environment.NewLine);
// 使用内存缓存
services.AddMemoryCache();
// 分布式内存缓存
services.AddDistributedMemoryCache();
}
services.AddSingleton<ICaching, Caching>();
//File.AppendAllText(path, "添加缓存结束" + Environment.NewLine);
}
}