using CSRedis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
namespace Fuel.Infrastructure.Extension
{
///
/// redis 扩展方法
///
public static class RedisServiceCollectionExtension
{
public static IServiceCollection AddRedisClients(this IServiceCollection services, RedisOptions options)
{
var redisConfig = options;
CSRedisClient redisClient = null;
List panams = new List();
if (redisConfig != null)
{
//暂时不支持多个数据库连接
//var config = redis.FirstOrDefault();
if (redisConfig.Sentinels != null && redisConfig.Sentinels.Any())
{
//"127.0.0.1:6379,password=123,defaultDatabase=13,prefix=key前辍"
redisClient =
new CSRedisClient(
$"{redisConfig.ConnectionString},defaultDatabase={redisConfig.DataBase},prefix={redisConfig.PrefixKey}",
redisConfig.Sentinels);
}
else
{
//"127.0.0.1:6379,password=123,defaultDatabase=13,prefix=key前辍"
redisClient =
new CSRedisClient(
$"{redisConfig.ConnectionString},password={redisConfig.Password},defaultDatabase={redisConfig.DataBase},prefix={redisConfig.PrefixKey}");
}
}
CoreRedisHelper.AddClient(options.KeyName, redisClient);
if (CoreRedisHelper.redisHelpers.Any() && CoreRedisHelper.redisHelpers.Count <= 1)
{
RedisHelper.Initialization(redisClient);
services.AddSingleton(new CSRedisCache(RedisHelper.Instance));
}
return services;
}
///
/// 单个redis 兼容旧版本
///
///
///
public static IServiceCollection UseRedisClient(this IServiceCollection services, RedisOptions redisOptions )
{
//var redisOptions = new RedisOptions();
//configuration.GetSection("Redis").Get();
services.AddRedisClients(redisOptions);
return services;
}
///
/// 多个redis database 的问题
///
///
///
public static IServiceCollection UseRedisClients(this IServiceCollection services,List redisClients)
{
if (redisClients.Any())
{
redisClients = redisClients.OrderByDescending(p => p.Default).ToList();
foreach (var client in redisClients)
{
if (!string.IsNullOrWhiteSpace(client.KeyName))
{
services.AddRedisClients(client);
}
}
}
return services;
}
}
}