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.

66 lines
2.4 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 Admin.Core.Common;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using System;
namespace Admin.Core.Extensions
{
/// <summary>
/// Redis缓存 启动服务
/// </summary>
public static class RedisCacheSetup
{
public static void AddRedisCacheSetup(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();
// 配置启动Redis服务虽然可能影响项目启动速度但是不能在运行的时候报错所以是合理的
services.AddSingleton<ConnectionMultiplexer>(sp =>
{
//获取连接字符串
string redisConfiguration = Appsettings.app(new string[] { "Redis", "ConnectionString" });
var configuration = ConfigurationOptions.Parse(redisConfiguration, true);
configuration.ResolveDns = true;
return ConnectionMultiplexer.Connect(configuration);
//return GetRedisConnection();
});
}
/// <summary>
/// 核心代码,获取连接实例
/// 通过双if 加lock的方式实现单例模式
/// </summary>
/// <returns></returns>
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而且我的是没有设置密码。");
}
}
}
}