public void Configure(IServiceCollection services, IConfiguration configuration) { RedisOptions cache = configuration.GetSection(nameof(RedisOptions)).Get <RedisOptions>(); services.AddStackExchangeRedisCache(options => { options.Configuration = cache.Connection; options.InstanceName = cache.InstanceName; }); services.Configure <RedisOptions>(configuration.GetSection(nameof(RedisOptions))); }
/// <summary> /// Redis计数器 /// </summary> /// <param name="services"></param> /// <param name="options"></param> /// <returns></returns> public static IServiceCollection AddRedisCounter(this IServiceCollection services, Action <RedisOptions> options) { var opts = new RedisOptions(); options.Invoke(opts); if (string.IsNullOrWhiteSpace(opts.ConnectionString)) { throw new ArgumentException("Redis计数器,缺少Redis连接字符串"); } services.AddSingleton(opts); services.AddSingleton <IRateLimitCounterStore, RedisRateLimitCounterStore>(); return(services); }
public void InstallSerive(IServiceCollection services, IConfiguration configuration) { var options = new RedisOptions(); configuration.GetSection(nameof(RedisOptions)).Bind(options); if (options.Enabled) { services.AddSingleton(options); services.AddSingleton <RedisServerService>(); services.AddSingleton <IRedisService, RedisService>(); services.AddSingleton <ICacheService, RedisCacheService>(); } }
public DefaultAuthenticationHandler( IOptionsMonitor <DefaultAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IDataProtectionProvider provider, IDataSerializer <AuthenticationTicket> serializer, IOptionsMonitor <RedisOptions> optionsAccessor) : base(options, logger, encoder, clock) { var dataProtector = provider.CreateProtector(Startup.DefaultConfig.SecretKey); _format = new DefaultAuthenticationDataFormat(dataProtector, serializer); _redisOptions = optionsAccessor.CurrentValue; }
internal static IServiceCollection AddInfrastructure(this IServiceCollection services) { IConfiguration configuration; using (var serviceProvider = services.BuildServiceProvider()) { configuration = serviceProvider.GetService <IConfiguration>(); } services.Configure <AppOptions>(configuration.GetSection("app")); services.AddMemoryCache(); var redisSection = configuration.GetSection("redis"); var redisOptions = new RedisOptions(); redisSection.Bind(redisOptions); services.Configure <RedisOptions>(redisSection); services.AddDistributedRedisCache(r => { r.Configuration = redisOptions.ConnectionString; r.InstanceName = redisOptions.Instance; }); services.Configure <EfOptions>(configuration.GetSection("ef")); services.AddEntityFrameworkSqlServer() .AddEntityFrameworkInMemoryDatabase(); services.AddTransient <ICommandDispatcher, InMemoryCommandDispatcher>(); services.AddTransient <IIntegrationEventDispatcher, InMemoryIntegrationEventDispatcher>(); services.AddTransient <IQueryDispatcher, InMemoryQueryDispatcher>(); services.AddTransient <IDispatcher, InMemoryDispatcher>(); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); services.Scan(s => s.FromAssemblies(assemblies) .AddClasses(c => c.AssignableTo(typeof(ICommandHandler <>))) .AsImplementedInterfaces() .WithTransientLifetime()); services.Scan(s => s.FromAssemblies(assemblies) .AddClasses(c => c.AssignableTo(typeof(IIntegrationEventHandler <>))) .AsImplementedInterfaces() .WithTransientLifetime()); services.Scan(s => s.FromAssemblies(assemblies) .AddClasses(c => c.AssignableTo(typeof(IQueryHandler <,>))) .AsImplementedInterfaces() .WithTransientLifetime()); return(services); }
private int GetRedisOptionsHashCode(RedisOptions redisOptions) { string cfg = ""; if (redisOptions.ConfigurationOptions != null) { cfg = System.Text.Json.JsonSerializer.Serialize(redisOptions.ConfigurationOptions); } else { cfg = redisOptions.Configuration; } return(cfg.GetHashCode()); }
public RedisMessageInbox(IDistributedCache cache, InboxOptions inboxOptions, RedisOptions redisOptions, ILogger <RedisMessageInbox> logger) { if (string.IsNullOrWhiteSpace(redisOptions.Instance)) { throw new ArgumentException("Redis instance cannot be empty.", nameof(redisOptions.Instance)); } _cache = cache; _logger = logger; _enabled = inboxOptions.Enabled; _expiry = inboxOptions.ExpirySeconds; _instance = redisOptions.Instance; }
private void ConfigureRedis(IServiceCollection services) { var optionsSection = Configuration.GetSection("redis"); var options = new RedisOptions(); optionsSection.Bind(options); services.Configure <RedisOptions>(optionsSection); services.AddDistributedRedisCache(x => { x.Configuration = options.ConnectionString; x.InstanceName = options.Instance; }); }
public static IServiceCollection AddRedis(this IServiceCollection services, Action <RedisOptions> optionsAction) { var opt = new RedisOptions(); optionsAction?.Invoke(opt); var redis = ConnectionMultiplexer.Connect(opt.RedisConnection); var db = redis.GetDatabase(); Console.WriteLine("Redis Ping:" + db.Ping()); services.AddSingleton(opt); services.AddSingleton(redis); return(services); }
public async Task <ConnectionMultiplexer> ConnectAsync(RedisOptions redisOptions, CancellationToken token) { int _hashCode = GetRedisOptionsHashCode(redisOptions); token.ThrowIfCancellationRequested(); ConnectionMultiplexer connection = null; _connections.TryGetValue(_hashCode, out connection); if (connection != null) { return(connection); } var connectionLock = _connectionLocks.GetOrAdd(_hashCode, k => { return(new SemaphoreSlim(initialCount: 1, maxCount: 1)); }); await connectionLock.WaitAsync(token); try { _connections.TryGetValue(_hashCode, out connection); if (connection != null) { return(connection); } if (redisOptions.ConfigurationOptions != null) { connection = await ConnectionMultiplexer.ConnectAsync(redisOptions.ConfigurationOptions); } else { connection = await ConnectionMultiplexer.ConnectAsync(redisOptions.Configuration); } _logger.LogInformation("创建新的Redis链接"); _connections.TryAdd(_hashCode, connection); } catch (Exception e) { _logger.LogError(e, $"Connect Error"); } finally { connectionLock.Release(); } return(connection); }
public static IServiceCollection AddRedisCacheService( this IServiceCollection serviceCollection, Func <RedisOptions, RedisOptions> redisOptions = null ) { var _redisOptions = new RedisOptions(); _redisOptions = redisOptions?.Invoke(_redisOptions) ?? _redisOptions; config = _redisOptions; connection = ConnectionMultiplexer.Connect(GetSystemOptions()); _db = connection.GetDatabase(config.RedisIndex); _sub = connection.GetSubscriber(); return(serviceCollection); }
public static ParallelQueueProducerOptions <TEntity> UseRedis <TEntity>( this ParallelQueueProducerOptions <TEntity> options, Action <RedisOptions> redisOptions) { options.SetProducer((sp, name) => { RedisOptions ro = new RedisOptions(); redisOptions?.Invoke(ro); ILogger <QueueProducer <TEntity> > logger = sp.GetRequiredService <ILogger <QueueProducer <TEntity> > >(); RedisConnectionManager connManager = sp.GetRequiredService <RedisConnectionManager>(); return(new QueueProducer <TEntity>(name, ro, connManager, logger)); }); return(options); }
public void InstallServices(IServiceCollection services, IConfiguration configuration) { var redisOptions = new RedisOptions(); configuration.GetSection(nameof(RedisOptions)).Bind(redisOptions); services.AddSingleton(redisOptions); if (redisOptions.Enabled) { services.AddStackExchangeRedisCache(options => options.Configuration = redisOptions.ConnectionString); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); } }
public static IUkiyoBuilder AddRedis(this IUkiyoBuilder builder, RedisOptions options) { if (!builder.TryRegister(RegistryName)) { return(builder); } builder.Services.AddStackExchangeRedisCache(o => { o.Configuration = options.ConnectionString; o.InstanceName = options.Instance; }); return(builder); }
public RedisLobby(string connectionAddress, Func <string, long, bool> publishTimingStats = null) { if (string.IsNullOrEmpty(connectionAddress)) { throw new ArgumentNullException(nameof(connectionAddress)); } var splitUp = connectionAddress.Split(new char[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries); this.opt = new RedisOptions(); this.opt.Host = splitUp[0]; this.opt.Port = int.Parse(splitUp[1]); this.publishTimingStats = publishTimingStats ?? new Func <string, long, bool>((n, d) => (true)); }
public QueueProducer(string name, RedisOptions redisOptions, RedisConnectionManager connectionManager, ILogger <QueueProducer <TEntity> > logger) { _redisOptions = redisOptions; _connectionManager = connectionManager; _logger = logger; _instance = _redisOptions.InstanceName ?? string.Empty; _queueRedisKey = $"{_instance}{name}"; _queueType = _redisOptions.QueueType; if (_queueType == QueueType.Bag) { _queueType = QueueType.FIFO; } _stopTokenSource = new CancellationTokenSource(); }
public RedisRateLimiterTests() { var options = Substitute.For <IOptionsSnapshot <RedisOptions> >(); var redisOptions = new RedisOptions(); redisOptions.Endpoints.Add(new ServerEndPoint() { Host = "localhost", Port = 6379 }); options.Value.Returns(redisOptions); var redisDataBaseProvider = new RedisDataBaseProvider(options); var manager = new RedisManager(redisDataBaseProvider); _database = redisDataBaseProvider.GetDatabase(); _limiter = new RedisRateLimiter(manager); }
public RedisSocketServer( IServiceProvider services, LocalStage localStage, ITelemetry telemetry, ILogger <RedisSocketServer> logger, IOptions <NanoServiceOptions> serviceOptions, IOptions <RedisOptions> redisOptions) { this._services = services; this._serviceOptions = serviceOptions.Value; this._redisOptions = redisOptions.Value; this._localStage = localStage; this._telemetry = telemetry; _logger = logger; }
/// <summary> /// 注入RedisCache /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <returns></returns> public static IApplicationBuilder UseRedisCache(this IApplicationBuilder app, Action <RedisOptions> options = null) { RedisOptions config = null; options(config); if (config == null) { config = new RedisOptions { host = "localhost", port = 6379 } } ; return(app); } }
public KafkaManualOffsetProvider(IOptions <KafkaOption> kafkaOption, IServiceProvider serviceProvider, IOptions <RedisOptions> redisOption, IDistributedCache distributedCache, ILogger <KafkaScribeProvider> logger) { _logger = logger; _serviceProvider = serviceProvider; _kafkaOption = kafkaOption.Value; _redisOptions = redisOption.Value; _distributedCache = distributedCache; _consumers = new Dictionary <string, List <IMessageConsumer> >(); _offset = new ConcurrentDictionary <string, long>(); _pre_offset = new ConcurrentDictionary <string, long>(); _timer = new Timer(SaveOffset, null, TimeSpan.Zero, TimeSpan.FromSeconds(3)); }
private RedisHubLifetimeManager <Hub> CreateLifetimeManager(TestRedisServer server, MessagePackHubProtocolOptions messagePackOptions = null, NewtonsoftJsonHubProtocolOptions jsonOptions = null) { var options = new RedisOptions() { ConnectionFactory = async(t) => await Task.FromResult(new TestConnectionMultiplexer(server)) }; messagePackOptions = messagePackOptions ?? new MessagePackHubProtocolOptions(); jsonOptions = jsonOptions ?? new NewtonsoftJsonHubProtocolOptions(); return(new RedisHubLifetimeManager <Hub>( NullLogger <RedisHubLifetimeManager <Hub> > .Instance, Options.Create(options), new DefaultHubProtocolResolver(new IHubProtocol[] { new NewtonsoftJsonHubProtocol(Options.Create(jsonOptions)), new MessagePackHubProtocol(Options.Create(messagePackOptions)), }, NullLogger <DefaultHubProtocolResolver> .Instance))); }
public LocationInfoManager(IPublisherService publisherService, IMapper mapper, ILocationInfoDal locationInfoDal, ICacheManager cacheManager, IObjectDataConverter objectDataConverter, IDistributedCache distributedCache, IOptions <LocationOptions> locationOptions, IOptions <RedisOptions> redisOptions) { _locationInfoDal = locationInfoDal; _mapper = mapper; _publisherService = publisherService; _cacheManager = cacheManager; _objectDataConverter = objectDataConverter; _distributedCache = distributedCache; _locationOptions = locationOptions.Value; _redisOptions = redisOptions.Value; }
public static IConveyBuilder AddRedis(this IConveyBuilder builder, RedisOptions options) { if (!builder.TryRegister(RegistryName)) { return(builder); } builder.Services .AddSingleton(options) .AddSingleton <IConnectionMultiplexer>(sp => ConnectionMultiplexer.Connect(options.ConnectionString)) .AddTransient(sp => sp.GetRequiredService <IConnectionMultiplexer>().GetDatabase(options.Database)) .AddStackExchangeRedisCache(o => { o.Configuration = options.ConnectionString; o.InstanceName = options.Instance; }); return(builder); }
public void ConfigureContainer(ContainerBuilder builder) { builder.RegisterInstance(this.Configuration).AsImplementedInterfaces(); RedisOptions redisOptions = new RedisOptions(); Configuration.GetSection("Redis").Bind(redisOptions); builder.AddRedis(redisOptions) .AddUnitOfWork(unitOfWorkProvider => { unitOfWorkProvider.AddEntityFramework <ClubContext>(UnitOfWorkNames.EntityFramework, repositoryContainer => { repositoryContainer.RegisterModule <EntityFrameworkModule>(); }); }); builder.RegisterModule <CoreModule>(); }
/// <summary> /// 将模块服务添加到依赖注入服务容器中 /// </summary> /// <param name="services">依赖注入服务容器</param> /// <returns></returns> public override IServiceCollection AddServices(IServiceCollection services) { IConfiguration configuration = services.GetConfiguration(); RedisOptions redisOptions = configuration.GetSection("Hybrid:Redis").Get <RedisOptions>(); _enabled = redisOptions.IsEnabled; if (!_enabled) { return(services); } services.RemoveAll(typeof(IDistributedCache)); services.AddStackExchangeRedisCache(opts => { opts.Configuration = redisOptions.Configuration; opts.InstanceName = redisOptions.InstanceName; }); return(services); }
private RedisHubLifetimeManager <MyHub> CreateLifetimeManager(TestRedisServer server, MessagePackHubProtocolOptions messagePackOptions = null, JsonHubProtocolOptions jsonOptions = null) { var options = new RedisOptions() { Factory = t => new TestConnectionMultiplexer(server) }; messagePackOptions = messagePackOptions ?? new MessagePackHubProtocolOptions(); jsonOptions = jsonOptions ?? new JsonHubProtocolOptions(); return(new RedisHubLifetimeManager <MyHub>( NullLogger <RedisHubLifetimeManager <MyHub> > .Instance, Options.Create(options), new DefaultHubProtocolResolver(new IHubProtocol[] { new JsonHubProtocol(Options.Create(jsonOptions)), new MessagePackHubProtocol(Options.Create(messagePackOptions)), }, NullLogger <DefaultHubProtocolResolver> .Instance))); }
/// <summary> /// Extension для инициализации SignalR через Redis /// </summary> /// <param name="serverBuilder"></param> /// <param name="options">Настройки подключения Redis</param> /// <returns></returns> public static ISignalRServerBuilder AddRedisBackPlane(this ISignalRServerBuilder serverBuilder, RedisOptions options) { var serviceProvider = serverBuilder.Services.BuildServiceProvider(); var logger = serviceProvider.GetService <ILogger>(); serverBuilder .AddStackExchangeRedis( o => { o.ConnectionFactory = async writer => { ConnectionMultiplexer connection = null; try { var config = ConfigurationOptions.Parse(options.Configuration); config.AbortOnConnectFail = false; connection = await ConnectionMultiplexer.ConnectAsync(config, writer); } catch (Exception ex) { logger.Fatal("Ошибка инициализации Redis", ex); } connection.ConnectionFailed += (_, e) => { logger.Error($"Ошибка подключения к Redis. Configuration: {connection.Configuration}", e.Exception); }; if (!connection.IsConnected) { logger.Error($"Ошибка подкючения к Redis. Configuration: {connection.Configuration}"); } return(connection); }; }); return(serverBuilder); }
/// <summary> /// 添加Redis /// </summary> /// <returns></returns> public DependencyInjectionService AddRedis() { RedisOptions options = new RedisOptions { HostName = "127.0.0.1", Port = 6379, Password = "******", DefaultDatabase = string.Empty, WriteBuffer = 10240, Prefix = string.Empty, TryIt = 3, PoolSize = 50, SSL = false, ExpireSeconds = 60, EnvName = string.Empty }; _services.TryAddSingleton <IRedisHelper>(new CsRedisHelper(options)); return(_dependencyInjectionConfiguration); }
/// <summary> /// 添加Rye框架对Redis缓存的支持 /// </summary> /// <param name="serviceCollection"></param> /// <param name="action">配置Redis 配置选项</param> /// <returns></returns> public static IServiceCollection AddRedisCache(this IServiceCollection serviceCollection, Action <RedisOptions> action) { var options = new RedisOptions(); action?.Invoke(options); serviceCollection.Configure(action); var redisClient = new CSRedisClient(new RedisConnectionBuilder().BuildConnectionString(options)); RedisHelper.Initialization(redisClient); serviceCollection.AddSingleton <IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance)); serviceCollection.TryAddSingleton <IRedisStore, RedisStore>(); serviceCollection.RemoveAll <ICacheStore>(); serviceCollection.TryAddSingleton <ICacheStore>(service => service.GetRequiredService <IRedisStore>()); serviceCollection.RemoveAll <IMutilCacheStore>(); serviceCollection.TryAddSingleton <IMutilCacheStore, MutilCacheStore>(); serviceCollection.RemoveAll <IAppCacheStore>(); serviceCollection.TryAddSingleton <IAppCacheStore, AppRedisCacheStore>(); return(serviceCollection); }
private static ConnectionMultiplexer ConnectToRedis(RedisOptions options, ILogger logger) { var loggerTextWriter = new LoggerTextWriter(logger); if (options.Factory != null) { return(options.Factory(loggerTextWriter)); } if (options.Options.EndPoints.Any()) { return(ConnectionMultiplexer.Connect(options.Options, loggerTextWriter)); } var configurationOptions = new ConfigurationOptions(); configurationOptions.EndPoints.Add(IPAddress.Loopback, 0); configurationOptions.SetDefaultPorts(); return(ConnectionMultiplexer.Connect(configurationOptions, loggerTextWriter)); }