Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:EasyCaching.InMemory.DefaultInMemoryCachingProvider"/> class.
        /// </summary>
        /// <param name="name">Name.</param>
        /// <param name="cache">Cache.</param>
        /// <param name="options">Options.</param>
        /// <param name="factory">Distributed lock factory</param>
        /// <param name="loggerFactory">Logger factory.</param>
        public DefaultInMemoryCachingProvider(
            string name,
            IEnumerable <IInMemoryCaching> cache,
            InMemoryOptions options,
            IDistributedLockFactory factory = null,
            ILoggerFactory loggerFactory    = null)
            : base(factory, options)
        {
            this._name    = name;
            this._cache   = cache.Single(x => x.ProviderName == _name);
            this._options = options;
            this._logger  = loggerFactory?.CreateLogger <DefaultInMemoryCachingProvider>();

            this._cacheStats = new CacheStats();

            this.ProviderName          = _name;
            this.ProviderType          = CachingProviderType.InMemory;
            this.ProviderStats         = _cacheStats;
            this.ProviderMaxRdSecond   = _options.MaxRdSecond;
            this.IsDistributedProvider = false;

            _info = new ProviderInfo
            {
                CacheStats            = _cacheStats,
                EnableLogging         = options.EnableLogging,
                IsDistributedProvider = IsDistributedProvider,
                LockMs         = options.LockMs,
                MaxRdSecond    = options.MaxRdSecond,
                ProviderName   = ProviderName,
                ProviderType   = ProviderType,
                SerializerName = options.SerializerName,
                SleepMs        = options.SleepMs,
                CacheNulls     = options.CacheNulls,
            };
        }
Ejemplo n.º 2
0
 public CheckingAccountTransactionDomain(ICurrencyRepository currencyRepository, ICheckingAccountTransactionRepository checkingAccountTransactionRepository, IConnectionMultiplexer connectionMultiplexer, IDistributedLockFactory distributedLockFactory)
 {
     this.currencyRepository = currencyRepository;
     this.checkingAccountTransactionRepository = checkingAccountTransactionRepository;
     this.connectionMultiplexer  = connectionMultiplexer;
     this.distributedLockFactory = distributedLockFactory;
 }
Ejemplo n.º 3
0
        protected DistributedLockTest(string name, IDistributedLockFactory lockFactory, ITestOutputHelper output)
        {
            _name        = name;
            _lockFactory = lockFactory;

            _output = output;
        }
Ejemplo n.º 4
0
 public NumberPoolService(IRedisClient redis)
 {
     _redis          = redis;
     _redLockFactory = RedLockFactory.Create(new List <RedLockMultiplexer> {
         _redis.Connection
     });
 }
Ejemplo n.º 5
0
        public CacheHelper(string name,
                           ICacheProviderFactory cpf,
                           IDistributedLockFactory factory,
                           IKeyFormatter formatter,
                           IValueSerializer serializer,
                           RecyclableMemoryStreamManager manager,
                           IOptionsMonitor <CacheOptions> options,
                           int defaultTTl)
        {
            if (cpf == null)
            {
                throw new ArgumentNullException(nameof(cpf));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            _factory   = factory ?? throw new ArgumentNullException(nameof(factory));
            _formatter = formatter;
            _manager   = manager;

            _options    = options.CurrentValue;
            _defaultTTl = defaultTTl < 1 ? _options.DefaultTtl : defaultTTl;
            _provider   = cpf.Create($"{_options.KeyPrefix}/Cache/{_name = name}");
            _serializer = _options.CompressValue ? new CompressionSerializer(serializer, manager) : serializer;
        }
Ejemplo n.º 6
0
 public BookshelfService(IDatabase redisDatabase, IDistributedLockFactory distributedLockFactory, AnfDbContext dbContext, ReadingManager readingManager, IOptions <BookshelfOptions> bookshelfOptions)
 {
     this.redisDatabase          = redisDatabase;
     this.distributedLockFactory = distributedLockFactory;
     this.dbContext        = dbContext;
     this.readingManager   = readingManager;
     this.bookshelfOptions = bookshelfOptions;
 }
Ejemplo n.º 7
0
 public Int64CacheProxy(object any,
                        ICacheProviderFactory cpf,
                        IDistributedLockFactory factory,
                        IKeyFormatter formatter,
                        IValueSerializer serializer,
                        RecyclableMemoryStreamManager manager,
                        IOptionsMonitor <CacheOptions> options)
     : base(any) =>
Ejemplo n.º 8
0
 protected DistributedLockManager(IDistributedLockFactory <TIdentity> lockFactory,
                                  TimeSpan defaultTTL, Policy retryPolicy,
                                  params IConnection[] connections)
 {
     DistributedLockFactory = lockFactory;
     DefaultTTL             = defaultTTL;
     RetryPolicy            = retryPolicy;
     Connections            = connections;
 }
        public MyOrderHostedService(IServiceProvider serviceProvider)
        {
            var scop = serviceProvider.CreateScope();

            _productService = scop.ServiceProvider.GetService <IProductService>();
            _orderService   = scop.ServiceProvider.GetService <IOrderService>();
            _saleService    = scop.ServiceProvider.GetService <ISaleService>();
            _lockFactory    = scop.ServiceProvider.GetService <IDistributedLockFactory>();
        }
        public GetAggregateWithLockTest()
        {
            var eventStore         = new TestEventStore();
            var eventStoreSettings = new TestEventStoreSettings {
                SessionLockEnabled = true
            };

            _distributedLockFactory = A.Fake <IDistributedLockFactory>();
            _session = new Session(new Repository(eventStore), eventStoreSettings, _distributedLockFactory);
        }
Ejemplo n.º 11
0
 public Session(IRepository repository, EventStoreSettings eventStoreSettings, IDistributedLockFactory distributedLockFactory)
 {
     _repository         = repository ?? throw new ArgumentNullException(nameof(repository));
     _trackedAggregates  = new Dictionary <string, AggregateDescriptor>();
     _eventStoreSettings = eventStoreSettings;
     if (eventStoreSettings != null && eventStoreSettings.SessionLockEnabled)
     {
         _sessionLockEnabled     = true;
         _distributedLockFactory = distributedLockFactory ?? throw new ArgumentNullException(nameof(distributedLockFactory));
     }
 }
Ejemplo n.º 12
0
 public SaveWithLockTest()
 {
     _eventStore         = new TestInMemoryEventStore();
     _rep                = new Repository(_eventStore);
     _eventStoreSettings = new TestEventStoreSettings {
         SessionLockEnabled = true
     };
     _distributedLockFactory = A.Fake <IDistributedLockFactory>();
     _session   = new Session(_rep, _eventStoreSettings, _distributedLockFactory);
     _aggregate = new TestAggregateNoParameterLessConstructor(2);
 }
Ejemplo n.º 13
0
 public NodeUpdateListener(
     IDistributedLockFactory lockFactory,
     IConnectionMultiplexer multiplexer,
     ILogger <NodeUpdateListener> logger,
     IServiceProvider provider
     )
 {
     this.lockFactory = lockFactory;
     this.multiplexer = multiplexer;
     this.logger      = logger;
     this.provider    = provider;
 }
 public ShoppingController(
     IDistributedLockFactory lockFactory,
     IProductService service,
     IOrderService orderService,
     ISaleService saleService)
 {
     _lockFactory    = lockFactory;
     _productService = service;
     _orderService   = orderService;
     _saleService    = saleService;
     _redisDb        = ConnectionMultiplexer.Connect("127.0.0.1:6379").GetDatabase(1);
 }
 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()
     });
 }
Ejemplo n.º 16
0
 public CreateProxyOptions(ICacheProviderFactory cacheProviderFactory,
                           IDistributedLockFactory distributedLockFactory,
                           IKeyFormatter keyFormatter,
                           IValueSerializer valueSerializer,
                           RecyclableMemoryStreamManager streamManager,
                           CacheOptions options)
 {
     CacheProviderFactory   = cacheProviderFactory;
     DistributedLockFactory = distributedLockFactory;
     KeyFormatter           = keyFormatter;
     ValueSerializer        = valueSerializer;
     StreamManager          = streamManager;
     Options = options;
 }
 public RedisEventSubscriber(
     IRedisClient redis,
     string applicationName,
     string environment,
     IDistributedLockFactory distributedLockFactory,
     DistributedLockSettings lockSettings = null)
 {
     _redisClient            = redis;
     _messageQueueRepository = new MessageQueueRepository(_redisClient, environment, applicationName);
     _applicationName        = applicationName;
     _environment            = environment;
     _distributedLockFactory = distributedLockFactory;
     _lockSettings           = lockSettings ?? new DistributedLockSettings();
 }
Ejemplo n.º 18
0
        public DefaultDiskCachingProvider(string name,
                                          DiskOptions options,
                                          IDistributedLockFactory factory = null,
                                          ILoggerFactory loggerFactory    = null)
            : base(factory, options)
        {
            this._name    = name;
            this._options = options;
            this._logger  = loggerFactory?.CreateLogger <DefaultDiskCachingProvider>();

            this._cacheKeysMap = new ConcurrentDictionary <string, string>();

            this._cacheStats = new CacheStats();

            this.ProviderName          = _name;
            this.ProviderType          = CachingProviderType.Disk;
            this.ProviderStats         = _cacheStats;
            this.ProviderMaxRdSecond   = _options.MaxRdSecond;
            this.IsDistributedProvider = false;

            _info = new ProviderInfo
            {
                CacheStats            = _cacheStats,
                EnableLogging         = options.EnableLogging,
                IsDistributedProvider = IsDistributedProvider,
                LockMs         = options.LockMs,
                MaxRdSecond    = options.MaxRdSecond,
                ProviderName   = ProviderName,
                ProviderType   = ProviderType,
                SerializerName = options.SerializerName,
                SleepMs        = options.SleepMs,
                CacheNulls     = options.CacheNulls,
            };

            Init();

            _saveKeyTimer = new Timer(SaveKeyToFile, null, TimeSpan.FromSeconds(10), TimeSpan.FromMinutes(2));
        }
 public RedLockController(IDistributedLockFactory distributedLockFactory, ProductService productService)
 {
     _distributedLockFactory = distributedLockFactory;
     _productService         = productService;
 }
Ejemplo n.º 20
0
 public ValuesController(IDistributedLockFactory distributedLockFactory)
 {
     _distributedLockFactory = distributedLockFactory;
 }
Ejemplo n.º 21
0
 public RedisMutex(IDistributedLockFactory lockFactory)
 {
     this.lockFactory = lockFactory;
 }
Ejemplo n.º 22
0
 protected DistributedLockTest(IDistributedLockFactory lockFactory, ILoggerFactory loggerFactory)
 {
     _lockFactory   = lockFactory;
     _loggerFactory = loggerFactory;
 }
Ejemplo n.º 23
0
 public ResourceLockerFactory(IDistributedLockFactory distributedLockFactory, IOptions <ResourceLockOptions> resourceLockOptions)
 {
     this.distributedLockFactory = distributedLockFactory;
     this.resourceLockOptions    = resourceLockOptions;
 }
Ejemplo n.º 24
0
 public DistributedLockManager(IDistributedLockFactory lockFactory, DistributedLockOptions lockOptions)
 {
     _lockFactory = lockFactory;
     _expiration  = lockOptions.Expiration;
 }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            {
                Parallel.For(0, 100, ndx =>
                {
                    Console.WriteLine(RandomName.GetFullName());
                });
            }

            Console.ReadLine();
            {
                User user = new User
                {
                    Id         = "1",
                    Name       = "张三1111",
                    CreateTime = DateTime.Now
                };
                user.Dict = new Dictionary <string, object>();
                user.Dict.Add("Id", 1);
                user.Dict.Add("Name", "张三");
                user.Info = new Info {
                    Picture = "picture"
                };
                user.Infos = new List <Info> {
                    new Info {
                        Picture = "info1"
                    },
                    new Info {
                        Picture = "info2"
                    },
                    new Info {
                        Picture = "info3"
                    },
                    new Info {
                        Picture = "info4"
                    },
                    new Info {
                        Picture = "info5"
                    }
                };

                var jj = user.ToMsgPackJson();

                var _dict = user.ToMsgPackBytes();

                var _dict1 = _dict.ToMsgPackObject <User>();

                var _user1 = user.ToMsgPackBytes().ToMsgPackObject <User>();

                var json = user.ToMsgPackJson(MessagePackSerializerResolver.UnixDateTimeOptions);

                var jsonBytes = json.ToMsgPackBytesFromJson(MessagePackSerializerResolver.UnixDateTimeOptions);

                var data = jsonBytes.ToMsgPackObject <User>(MessagePackSerializerResolver.UnixDateTimeOptions);

                //var dict = new Dictionary<string, object>();
                //dict.Add("Id", 1);
                //dict.Add("Name", "张三");



                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                var configuration = ConfigHelper.GetJsonConfig("appsettings.Test.json");

                IRedisService redisService = new RedisServiceProvider(configuration, null);

                string hashId = "User";

                //redisService.HashDelete(hashId, user.Id);

                //redisService.HashSet<User>(hashId, user.Id, user);

                var res = redisService.HashGet <User>(hashId, user.Id, serializer: new MessagePackRedisSerializer());

                string hashId2 = "User2";

                //redisService.HashDelete(hashId2, "2");

                //redisService.HashSet(hashId2, "2", "2");

                var res1 = redisService.HashGet <string>(hashId2, "2", serializer: new MessagePackRedisSerializer());

                string hashId3 = "User3";

                //redisService.HashDelete(hashId3, "3");

                //redisService.HashSet(hashId3, "3", "3");

                var res3 = redisService.HashGet <string>(hashId3, "3", serializer: new MessagePackRedisSerializer());


                Console.Read();



                redisService.StringSet <long>("test", 10);


                var stackConnects = configuration.GetSection <List <StackExchangeConnectionSettings> >("StackExchangeConnectionSettings");

                var endPoints = stackConnects.Where(c => c.ConnectType == ConnectTypeEnum.Read).ForEach(item => new RedLockEndPoint()
                {
                    EndPoint      = new DnsEndPoint(item.EndPoint, item.Port.ToInt()),
                    RedisDatabase = item.DefaultDb,
                    Password      = item.Password
                });

                IDistributedLockFactory _distributedLockFactory = RedLockFactory.Create(endPoints);

                string key   = "key";
                string token = Environment.MachineName;

                Parallel.For(0, 100, async ndx =>
                {
                    // resource 锁定的对象
                    // expiryTime 锁定过期时间,锁区域内的逻辑执行如果超过过期时间,锁将被释放
                    // waitTime 等待时间,相同的 resource 如果当前的锁被其他线程占用,最多等待时间
                    // retryTime 等待时间内,多久尝试获取一次
                    using (var redLock = await _distributedLockFactory.CreateLockAsync(
                               resource: key,
                               expiryTime: TimeSpan.FromSeconds(5),
                               waitTime: TimeSpan.FromSeconds(1),
                               retryTime: TimeSpan.FromMilliseconds(20)))
                    {
                        if (redLock.IsAcquired)
                        {
                            var count = redisService.StringGet <long>("test");

                            if (count > 0)
                            {
                                await redisService.StringIncrementAsync("test", -1);
                            }

                            Console.WriteLine($"{count}:{DateTime.Now} {Thread.ThreadId}");
                        }
                        else
                        {
                            Console.WriteLine($"获取锁失败:{DateTime.Now} {Thread.ThreadId}");
                        }
                    }

                    //using (await _asyncLock.LockAsync())
                    //{
                    //    var s = await redisService.StringIncrementAsync("test");
                    //    Console.WriteLine($"{s}");
                    //}

                    //if (!await redisService.LockTakeAsync(key, token, 10))
                    //{
                    //    return;
                    //}

                    //try
                    //{
                    //    // 模拟执行的逻辑代码花费的时间
                    //    await Task.Delay(new Random().Next(100, 500);
                    //    if (stockCount > 0)
                    //    {
                    //        stockCount--;
                    //    }
                    //    //var s = await redisService.StringIncrementAsync("test");
                    //    Console.WriteLine($"{stockCount}");
                    //}
                    //catch (Exception ex)
                    //{
                    //}
                    //finally
                    //{
                    //    await redisService.LockReleaseAsync(key, token);
                    //}
                });
            }
            Console.ReadKey();
        }
 public TestCachingProvider(string name, IEnumerable <IInMemoryCaching> cache, InMemoryOptions options, IDistributedLockFactory factory, ILoggerFactory loggerFactory = null) : base(name, cache, options, factory, loggerFactory)
 {
 }
 protected EasyCachingAbstractProvider(IDistributedLockFactory lockFactory, BaseProviderOptions options)
 {
     _lockFactory = lockFactory;
     _options     = options;
 }
Ejemplo n.º 28
0
 public LockServiceFactory(IDistributedLockFactory distributedLockFactory)
 {
     _distributedLockFactory = distributedLockFactory;
 }
 public void Dispose()
 {
     _factory = null;
 }
 public LockService(IDistributedLockFactory lockFactory)
 {
     _locks       = new Dictionary <string, IRedLock>();
     _lockFactory = lockFactory;
 }