using Admin.Core.Common;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
namespace Admin.Core.Extensions
{
///
/// Redis缓存 启动服务
///
public static class RedisCacheSetup
{
public static void AddRedisCacheSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddTransient();
// 配置启动Redis服务,虽然可能影响项目启动速度,但是不能在运行的时候报错,所以是合理的
services.AddSingleton(sp =>
{
//获取连接字符串
string redisConfiguration = Appsettings.app(new string[] { "Redis", "ConnectionString" });
var configuration = ConfigurationOptions.Parse(redisConfiguration, true);
configuration.ResolveDns = true;
return ConnectionMultiplexer.Connect(configuration);
//return GetRedisConnection();
});
}
///
/// 核心代码,获取连接实例
/// 通过双if 加lock的方式,实现单例模式
///
///
public static ConnectionMultiplexer GetRedisConnection()
{
try
{
//获取连接字符串
string redisConfiguration = Appsettings.app(new string[] { "Redis", "ConnectionString" });
var config = new ConfigurationOptions
{
AbortOnConnectFail = false,
AllowAdmin = true,
ConnectTimeout = 15000,//改成15s
SyncTimeout = 5000,
//Password = "Pwd",//Redis数据库密码
EndPoints = { redisConfiguration }// connectionString 为IP:Port 如”192.168.2.110:6379”
};
return ConnectionMultiplexer.Connect(config);
}
catch (Exception)
{
throw new Exception("Redis服务未启用,请开启该服务,并且请注意端口号,本项目使用的的6319,而且我的是没有设置密码。");
}
}
}
}