public void TestCancelBlockingLock() { var cts = new CancellationTokenSource(); var resource = $"testredislock:{Guid.NewGuid()}"; using (var redisLockFactory = RedLockFactory.Create(AllActiveEndPoints)) { using (var firstLock = redisLockFactory.CreateLock( resource, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1))) { Assert.That(firstLock.IsAcquired); cts.CancelAfter(TimeSpan.FromSeconds(2)); Assert.Throws <OperationCanceledException>(() => { using (var secondLock = redisLockFactory.CreateLock( resource, TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1), cts.Token)) { // should never get here Assert.Fail(); } }); } } }
public void TimeLock() { using (var redisLockFactory = RedLockFactory.Create(AllActiveEndPoints)) { var resource = $"testredislock:{Guid.NewGuid()}"; for (var i = 0; i < 10; i++) { var sw = Stopwatch.StartNew(); using (var redisLock = redisLockFactory.CreateLock(resource, TimeSpan.FromSeconds(30))) { sw.Stop(); logger.Info($"Acquire {i} took {sw.ElapsedTicks} ticks, success {redisLock.IsAcquired}"); sw.Restart(); } sw.Stop(); logger.Info($"Release {i} took {sw.ElapsedTicks} ticks, success"); } } }
public static IServiceCollection AddAppCaching(this IServiceCollection services, IWebHostEnvironment environment, IConfiguration configuration) { if (environment.IsDevelopment()) { services.AddDistributedMemoryCache(); } else { var distributedCacheSection = new DistributedCacheSection(); configuration.Bind(DistributedCacheSection.SectionName, distributedCacheSection); services.AddStackExchangeRedisCache(options => { options.Configuration = distributedCacheSection.Configuration; options.InstanceName = distributedCacheSection.InstanceName; }); services.AddSingleton <IConnectionMultiplexer>(provider => ConnectionMultiplexer.Connect($"{distributedCacheSection.Configuration},channelPrefix={distributedCacheSection.InstanceName}")); services.AddSingleton <IDistributedLockFactory>(provider => RedLockFactory.Create(new List <RedLockMultiplexer>() { new RedLockMultiplexer(provider.GetService <IConnectionMultiplexer>()) })); } return(services); }
public NumberPoolService(IRedisClient redis) { _redis = redis; _redLockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> { _redis.Connection }); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { // services.AddHostedService<MyRabbitMQConsumerHostedService>(); //services.AddHostedService<MyDirectConsumerHostedService>(); //services.AddDbContext<MyDbContext>(builder => //{ // builder.UseMySql("server=localhost;uid=root;pwd=root;database=shop;"); //}); services.AddDbContextPool <MyDbContext>(builder => { builder.UseMySql("server=localhost;uid=root;pwd=root;database=shop;"); }); services.AddScoped <ISaleService, SaleService>(); services.AddScoped <IProductService, ProductService>(); services.AddScoped <IOrderService, OrderService>(); var lockFactory = RedLockFactory.Create(new List <RedLockEndPoint>() { new DnsEndPoint("127.0.0.1", 6379) }); services.AddSingleton(typeof(IDistributedLockFactory), lockFactory); services.AddHostedService <MyOrderHostedService>(); }
public RedlockFactoryProvider(string redisHost) { Factory = RedLockFactory.Create(new List <RedLockEndPoint> { new DnsEndPoint(redisHost, 6379) }); }
/// <summary> /// Create instance of RedisLockFactory /// </summary> /// <returns>RedisLockFactory</returns> protected RedLockFactory CreateRedisLockFactory() { //get password and value whether to use ssl from connection string var password = string.Empty; var useSsl = false; foreach (var option in _connectionString.Value.Split(',').Where(option => option.Contains('='))) { switch (option.Substring(0, option.IndexOf('=')).Trim().ToLowerInvariant()) { case "password": password = option.Substring(option.IndexOf('=') + 1).Trim(); break; case "ssl": bool.TryParse(option.Substring(option.IndexOf('=') + 1).Trim(), out useSsl); break; } } var points = GetEndPoints().Select(endPoint => new RedLockEndPoint { EndPoint = endPoint, Password = password, Ssl = useSsl }).ToList(); return(RedLockFactory.Create(points)); }
private async Task <TResult> PerformInLockAsync <TResult>(string key, Func <Task <TResult> > actionTodo, TimeSpan?expireIn, CancellationToken cancellationToken) { if (key.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(key)); } if (actionTodo == null) { throw new ArgumentNullException(nameof(actionTodo)); } expireIn = expireIn ?? _expirityTime; using (var connection = ConnectionMultiplexer.Connect(_connectionString)) { var redLockMultiplexer = (RedLockMultiplexer)connection; redLockMultiplexer.RedisDatabase = _databaseId; using (var factory = RedLockFactory.Create(new List <RedLockMultiplexer> { connection }, null)) { var resource = GetLockKey(key); using (await factory.CreateLockAsync(resource, expiryTime: expireIn.Value, waitTime: _waitTime, retryTime: _retryTime, cancellationToken: cancellationToken)) { return(await actionTodo()); } } } }
public WebModuleEntry AddCache(IServiceCollection services, IConfiguration configuration) { services.AddSingleton <IDistributedCache, RedisCache>(); services.AddOptions <RedisCacheOptions>() .Configure(x => x.Configuration = configuration["ConnectionStringsCacheConnection"]); services.AddMemoryCache(); services.AddSingleton <IConnectionMultiplexer>(x => { var c = x.GetRequiredService <IConfiguration>(); var config = c["ConnectionStringsCacheConnection"]; return(ConnectionMultiplexer.Connect(config)); }); services.AddScoped(x => x.GetRequiredService <IConnectionMultiplexer>().GetDatabase()); services.AddSingleton <IDistributedLockFactory>(x => { var conn = x.GetRequiredService <IConnectionMultiplexer>(); return(RedLockFactory.Create(new List <RedLockMultiplexer> { new RedLockMultiplexer(conn) })); }); services.AddAutoCache(); return(this); }
private static void AddDbs() { // TODO: Clean this up. var environment = Environment.GetEnvironmentVariable("CORP_HQ_ENVIRONMENT"); var connString = new MongoUrl(Environment.GetEnvironmentVariable("MONGO_CONNECTION")); DbFactory.SetClient(new MongoClient(connString)); var dbFactory = new DbFactory(); var settingsCollection = dbFactory.GetCollection <Common.Model.Setting <Common.Model.Redis.Root> >(CollectionNames.Settings); var redisSettings = settingsCollection.AsQueryable().Where(s => s.Key == "redisConnection" && s.Environment == environment).First().Value; var connStr = string.Join(",", redisSettings.Hosts.Select(h => $"{h.Address}:{h.Port}")); var redisConnection = ConnectionMultiplexer.Connect(connStr); var redLockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> { redisConnection }); services.AddSingleton <IConnectionMultiplexer>(redisConnection); services.AddSingleton <RedLockFactory>(redLockFactory); // HACK to clean up the redis stuff in the mean time. Monitor.Instance.Disposed += (object sender, EventArgs args) => { redLockFactory.Dispose(); redisConnection.Dispose(); }; }
public DataFactory(DataFactoryOptions options, IConfiguration config) { //Conexão com o redis. string redisServer = "localhost:6379"; if (config != null) { redisServer = config.GetConnectionString(options.RedisConnectionStringName); } _lazyRedisClient = new Lazy <ConnectionMultiplexer>(() => { var redisOptions = ConfigurationOptions.Parse(redisServer); redisOptions.AbortOnConnectFail = false; return(ConnectionMultiplexer.Connect(redisOptions)); }, LazyThreadSafetyMode.ExecutionAndPublication); //Criação do RedLockFactory var existingConnectionMultiplexer1 = ConnectionMultiplexer.Connect(redisServer); var multiplexers = new List <RedLockMultiplexer> { existingConnectionMultiplexer1 }; _redLockFactory = RedLockFactory.Create(multiplexers); }
private static void NoSqlInit() { lazyRedisConnections = new Lazy <ConnectionMultiplexer>(() => { var options = ConfigurationOptions.Parse($"{ConfigHelper.RedisConnectionString}"); var muxer = ConnectionMultiplexer.Connect(options); muxer.ConnectionFailed += (sender, e) => { Console.WriteLine("redis failed: " + EndPointCollection.ToString(e.EndPoint) + "/" + e.ConnectionType); }; muxer.ConnectionRestored += (sender, e) => { Console.WriteLine("redis restored: " + EndPointCollection.ToString(e.EndPoint) + "/" + e.ConnectionType); }; return(muxer); }); lazyDistributedLockService = new Lazy <RedLockFactory>(() => { return(RedLockFactory.Create(new List <RedLockMultiplexer>() { lazyRedisConnections.Value })); }); }
public void TestPasswordConnection() { CheckSingleRedisLock( () => RedLockFactory.Create(new List <RedLockEndPoint> { PasswordedServer }, loggerFactory), RedLockStatus.Acquired); }
public RedisLockFactory(string connectionString) { var multiplexer = ConnectionMultiplexer.Connect(connectionString); _redLockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> { multiplexer }); }
public void TestNonDefaultRedisKeyFormat() { CheckSingleRedisLock( () => RedLockFactory.Create(new List <RedLockEndPoint> { NonDefaultRedisKeyFormatServer }), true); }
public async Task Start() { _multiplexer = await ConnectionMultiplexer.ConnectAsync(_connectionString); _redlockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> { new RedLockMultiplexer(_multiplexer) }); }
public void TestNonDefaultRedisDatabases() { CheckSingleRedisLock( () => RedLockFactory.Create(new List <RedLockEndPoint> { NonDefaultDatabaseServer }), true); }
public void TestPasswordConnection() { CheckSingleRedisLock( () => RedLockFactory.Create(new List <RedLockEndPoint> { PasswordedServer }), true); }
public void TestNonDefaultRedisKeyFormat() { CheckSingleRedisLock( () => RedLockFactory.Create(new List <RedLockEndPoint> { NonDefaultRedisKeyFormatServer }, loggerFactory), RedLockStatus.Acquired); }
public RedLockFactory GetRedLockFactory() { var multiplexers = new List <RedLockMultiplexer> { _redisConnection }; return(RedLockFactory.Create(multiplexers)); }
public BudgeterLock() { var endPoints = new List <RedLockMultiplexer> { RedisConnection.Connection }; Factory = RedLockFactory.Create(endPoints); }
public void TestRaceForQuorum() { var locksAcquired = 0; var lockKey = $"testredislock:{ThreadSafeRandom.Next(10000)}"; var tasks = new List <Task>(); for (var i = 0; i < 3; i++) { var task = new Task(() => { logger.Debug("Starting task"); using (var redisLockFactory = RedLockFactory.Create(AllActiveEndPoints)) { var sw = Stopwatch.StartNew(); using (var redisLock = redisLockFactory.CreateLock(lockKey, TimeSpan.FromSeconds(30))) { sw.Stop(); logger.Debug($"Lock method took {sw.ElapsedMilliseconds}ms to return, IsAcquired = {redisLock.IsAcquired}"); if (redisLock.IsAcquired) { logger.Debug($"Got lock with id {redisLock.LockId}, sleeping for a bit"); Interlocked.Increment(ref locksAcquired); // Sleep for long enough for the other threads to give up Thread.Sleep(TimeSpan.FromSeconds(2)); //Task.Delay(TimeSpan.FromSeconds(2)).Wait(); logger.Debug($"Lock with id {redisLock.LockId} done sleeping"); } else { logger.Debug("Couldn't get lock, giving up"); } } } }, TaskCreationOptions.LongRunning); tasks.Add(task); } foreach (var task in tasks) { task.Start(); } Task.WaitAll(tasks.ToArray()); Assert.That(locksAcquired, Is.EqualTo(1)); }
public void Start() { var endPoints = new List <RedLockEndPoint> { new DnsEndPoint("localhost", 6379) }; _distributedLockFactory = RedLockFactory.Create(endPoints); _acquireLockTimer = new Timer(async state => await TryAcquireLock((CancellationToken)state), _cts.Token, 0, _expirySecondsCount * 1000); }
public RedisCacheManager(RedisHelper redisHelper) { _redisHelper = redisHelper; var multiplexers = new List <RedLockMultiplexer> { _redisHelper.Connection }; _redLockFactory = RedLockFactory.Create(multiplexers); }
public async Task <RedLockFactory> GetRedisLockFactory() { var con = await GetConnect() as ConnectionMultiplexer; var multiplexers = new List <RedLockMultiplexer> { con, }; return(RedLockFactory.Create(multiplexers)); }
private static void InitLock(this IDistributedCache cache) { lock (_locker) { if (_redlockFactory == null) { _connection = (ConnectionMultiplexer?)(cache.GetType().GetField(nameof(_connection), BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(cache)) ?? throw new ArgumentException("fail to get ConnectionMultiplexer"); _redlockFactory = RedLockFactory.Create(new RedLockMultiplexer[] { _connection }); } } }
public RegisterDiscordBotCommandHandler(IDiscordSocketClientProvider provider, IServiceScopeFactory factory, IConfiguration configuration, ILogger <RegisterDiscordBotCommandHandler> logger, IRedisService redis) { _provider = provider; _factory = factory; _roleHelper = new DiscordRoleHelper(configuration); _logger = logger; _redis = redis; _lockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> { _redis.Connection() }); }
public RedlockProvider(params DnsEndPoint[] endpoints) { var redlockEndpoints = new List <RedLockEndPoint>(); foreach (var ep in endpoints) { redlockEndpoints.Add(ep); } _redlockFactory = RedLockFactory.Create(redlockEndpoints); }
private void AddRedLock(IServiceCollection services) { var redisConnectionString = Configuration.GetConnectionString("redis") ?? Configuration.GetConnectionString("HostedRedis"); var host = redisConnectionString.Split(':')[0]; var port = redisConnectionString.Split(':')[1]; var endPoints = new List <RedLockEndPoint> { new DnsEndPoint(host, int.Parse(port)), }; var redlockFactory = RedLockFactory.Create(endPoints); services.AddSingleton <RedLockFactory>(redlockFactory); }
private void Initialise(IConnectionMultiplexer cacheConnection, IConnectionMultiplexer lockConnection, IConnectionMultiplexer messagingConnection) { var redLockMultiPlexers = new List <RedLockMultiplexer> { new RedLockMultiplexer(lockConnection) }; var redLock = RedLockFactory.Create(redLockMultiPlexers); _createdDisposables.Add(redLock); _redisDistributedLockFactory = new RedisDistributedLockFactory(redLock); _redisExternalCache = new RedisExternalCache(cacheConnection.GetDatabase()); _redisFanOutBus = new RedisFanOutBus(messagingConnection.GetSubscriber()); }