Example #1
0
        /// <summary>
        /// 创建redis对象
        /// </summary>
        /// <returns></returns>
        public CacheClient CreateInstance()
        {
            CacheClient client = null;//获取Redis操作接口

            if (IsTrue)
            {
                switch (IsCacheName)
                {
                case CacheEnum.RedisCache:
                    client = new RedisCacheClient((DBEnum)RedisDB);
                    break;

                case CacheEnum.MemCache:
                    client = new MemCacheClient();
                    break;

                case CacheEnum.LocalCache:
                    client = new LocalClient();
                    break;
                }
            }
            else
            {
                cacheLog.Info(IsCacheName.ToString() + "缓存未启用");
            }
            return(client);
        }
Example #2
0
        public RedisLockTests()
        {
            var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());

            _cacheClient = new RedisCacheClient(muxer.GetDatabase());
            _locker      = new CacheLockProvider(_cacheClient);
        }
        public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            // We recommend to do this by using a IoC, for demo purposes a new instance is created manually.
            var cacheClient = new RedisCacheClient();

            dispatchOperation.Invoker = new CacheOperationInvoker(dispatchOperation.Invoker, cacheClient);
        }
Example #4
0
        public async Task <JsonResult> PesquisarJson(String termo)
        {
            db.Configuration.ProxyCreationEnabled = false;
            db.Configuration.LazyLoadingEnabled   = false;

            if (String.IsNullOrEmpty(termo))
            {
                return(Json(null, JsonRequestBehavior.AllowGet));
            }

            if (!await RedisCacheClient.ExistsAsync("Agencias"))
            {
                var agenciasBancarias = await db.AgenciasBancarias
                                        // .Where(a => a.Nome.Contains(termo) || termo.Contains(a.CodigoCompensacao.ToString()))
                                        .ToListAsync();

                await RedisCacheClient.AddAsync("Agencias", agenciasBancarias, new TimeSpan(0, 3, 0));
            }

            termo = termo.ToUpper();
            var lista = await RedisCacheClient.GetAsync <List <AgenciaBancaria> >("Agencias");

            return(Json(lista
                        .Where(a => a.Nome.Contains(termo) || termo.Contains(a.CodigoCompensacao.ToString())), JsonRequestBehavior.AllowGet));

            // return Json(agenciasBancarias, JsonRequestBehavior.AllowGet);
        }
Example #5
0
        // GET: Veiculos
        public async Task <ActionResult> Index(int?page)
        {
            if (!await RedisCacheClient.ExistsAsync("Veiculos"))
            {
                await RedisCacheClient.AddAsync("Veiculo", "", new TimeSpan(0, 3, 0));

                var veiculosDB = await db.Veiculos.ToListAsync();

                foreach (var item in veiculosDB)
                {
                    await RedisCacheClient.AddAsync("Veiculo:" + item.VeiculoId.ToString(), item, new TimeSpan(0, 3, 0));
                }
            }

            var veiculos = (await RedisCacheClient.SearchKeysAsync("Veiculo:*"))
                           .Select(p => RedisCacheClient.Get <Veiculo>(p)).OrderBy(x => x.VeiculoId).ToList() ??
                           await db.Veiculos.OrderBy(x => x.VeiculoId).ToListAsync();

            var pageNumber = page ?? 1;
            var paginacao  = await veiculos.ToPagedListAsync(pageNumber, 25);

            ViewBag.PageVeiculos = paginacao;

            return(View());
        }
Example #6
0
        // GET: Categorias
        public async Task <ActionResult> Index(int?page)
        {
            if (!await RedisCacheClient.ExistsAsync("Categoria"))
            {
                await RedisCacheClient.AddAsync("Categoria", "", new TimeSpan(0, 3, 0));

                var categoriaDB = await db.Categorias.ToListAsync();

                foreach (var item in categoriaDB)
                {
                    await RedisCacheClient.AddAsync("Categoria:" + item.CategoriaId.ToString(), item, new TimeSpan(0, 3, 0));
                }
            }

            var categorias = (await RedisCacheClient.SearchKeysAsync("Categoria:*"))
                             .Select(p => RedisCacheClient.Get <Categoria>(p)).OrderBy(x => x.CategoriaId).ToList() ??
                             await db.Categorias.OrderBy(x => x.CategoriaId).ToListAsync();

            var pageNumber = page ?? 1;
            var paginacao  = await categorias.ToPagedListAsync(pageNumber, 25);

            ViewBag.PageCategorias = paginacao;

            return(View());
        }
 public WeChatRedisCache(
     RedisCacheClient client,
     ILogger <WeChatRedisCache> logger)
 {
     _client = client;
     _logger = logger;
 }
Example #8
0
        private static async Task CacheSingleTest()
        {
            using (var cachePool = new CacheClientPoolAsync("Pool Test")
            {
                Serializer = GlobalSerializer
            })
            {
                try
                {
                    var cacheClient = new RedisCacheClient("localhost", "test")
                    {
                        DisableNotSupportedExceptions = true
                    };
                    cachePool.Add("test", cacheClient, StorageItemMode.ReadAndWrite);

                    for (var i = 0; i < 15; i++)
                    {
                        await cachePool.GetKeysAsync().ConfigureAwait(false);
                    }

                    for (var i = 0; i < 5000; i++)
                    {
                        var key = "test-" + i;
                        var kv  = await cachePool.GetAsync(key).ConfigureAwait(false);

                        var kv2 = await cachePool.SetAsync(key, "bla bla bla bla bla bla").ConfigureAwait(false);
                    }
                    Core.Log.InfoBasic("Done.");
                }
                catch (Exception ex)
                {
                    Core.Log.Write(ex);
                }
            }
        }
Example #9
0
        public RedisLockTests()
        {
            var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionString);

            _cacheClient = new RedisCacheClient(muxer);
            _locker      = new CacheLockProvider(_cacheClient);
        }
Example #10
0
 public CacheClient(RedisConfiguration config)
 {
     this.config    = config;
     ConnectionPool = new RedisCacheConnectionPoolManager(this.config);
     Client         = new RedisCacheClient(ConnectionPool, new Utf8JsonSerializer(), config);
     RedisDb        = Client.GetDbFromConfiguration();
     Db             = RedisDb.Database;
 }
Example #11
0
        public RedisService(RedisConfiguration redisConfiguration)
        {
            this.redisConfiguration = redisConfiguration;

            var merged = MergeConfiguration(redisConfiguration, RedisHosts(), RedisPassword());

            redisCacheClient = new RedisCacheClient(new RedisCacheConnectionPoolManager(merged), new SystemTextJsonSerializer(), merged);
        }
        public RedisAuthenticationSessionStore(string connectionString)
        {
            var muxer = ConnectionMultiplexer.Connect(connectionString);

            _client = new RedisCacheClient(new RedisCacheClientOptions
            {
                ConnectionMultiplexer = muxer
            });
        }
        public RedisCacheClientTests()
        {
            //if (!Settings.Current.UseAzureCache)
            //    return;

            var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());

            _cache = new RedisCacheClient(muxer.GetDatabase());
        }
Example #14
0
        public override async Task CanHaveMultipleQueueInstancesWithLockingAsync()
        {
            var muxer = SharedConnection.GetMuxer();

            using var cache      = new RedisCacheClient(new RedisCacheClientOptions { ConnectionMultiplexer = muxer, LoggerFactory = Log });
            using var messageBus = new RedisMessageBus(new RedisMessageBusOptions { Subscriber = muxer.GetSubscriber(), Topic = "test-queue", LoggerFactory = Log });
            var distributedLock = new CacheLockProvider(cache, messageBus, Log);

            await CanHaveMultipleQueueInstancesWithLockingImplAsync(distributedLock);
        }
        public void SetUp()
        {
            mockRedisConnection = new Mock <IConnectionMultiplexer>();
            mockRedisDb         = new Mock <IDatabase>();
            mockRedisConnection.Setup(c => c.GetDatabase(-1, null)).Returns(mockRedisDb.Object);

            redisCacheClient = new RedisCacheClient()
            {
                RedisConnection = mockRedisConnection.Object
            };
        }
Example #16
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Contato contato = await db.Contatos.FindAsync(id);

            db.Contatos.Remove(contato);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Contato:" + id);

            return(RedirectToAction("Index"));
        }
Example #17
0
        public RedisCacheClientTests()
        {
            if (Settings.Current.RedisConnectionInfo == null)
            {
                return;
            }

            var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());

            _cache = new RedisCacheClient(muxer.GetDatabase());
        }
Example #18
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Veiculo veiculo = await db.Veiculos.FindAsync(id);

            db.Veiculos.Remove(veiculo);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Veiculo:" + id);

            return(RedirectToAction("Index"));
        }
Example #19
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Funcionario funcionario = await db.Funcionarios.FindAsync(id);

            db.Funcionarios.Remove(funcionario);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Funcionario:" + id);

            return(RedirectToAction("Index"));
        }
Example #20
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Empresa empresa = await db.Empresas.FindAsync(id);

            db.Empresas.Remove(empresa);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Empresa:" + id);

            return(RedirectToAction("Index"));
        }
Example #21
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Banco banco = await db.Bancos.FindAsync(id);

            db.Bancos.Remove(banco);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Banco:" + banco.BancoId);

            return(RedirectToAction("Index"));
        }
Example #22
0
        public override async Task CanHaveMultipleQueueInstancesWithLockingAsync()
        {
            var muxer = SharedConnection.GetMuxer();

            using (var cache = new RedisCacheClient(muxer, loggerFactory: Log)) {
                using (var messageBus = new RedisMessageBus(muxer.GetSubscriber(), "test", loggerFactory: Log)) {
                    var distributedLock = new CacheLockProvider(cache, messageBus, Log);
                    await CanHaveMultipleQueueInstancesWithLockingImplAsync(distributedLock);
                }
            }
        }
Example #23
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Categoria categoria = await db.Categorias.FindAsync(id);

            db.Categorias.Remove(categoria);
            await db.SaveChangesAsync();

            await RedisCacheClient.RemoveAsync("Categoria:" + id);

            return(RedirectToAction("Index"));
        }
Example #24
0
        public RedisController(RedisCacheClient client, ConnectionMultiplexer redis, ILogger <RedisController> logger)
        {
            //这种获取每次都要连接一次redis
            //可以考虑实际使用的时候再GetDatabase
            _database = client.GetDatabase();
            _client   = client;

            //直接ConnectionMultiplexer单例。
            _redis    = redis;
            _database = _redis.GetDatabase();
            _logger   = logger;
        }
Example #25
0
 public CacheClient(RedisConfiguration config)
 {
     this.config = config;
     config.ConfigurationOptions.CertificateSelection += ConfigurationOptions_CertificateSelection;
     // MEMO: Don't do this in production (Dev only)
     // hack for local redis tls docker
     config.ConfigurationOptions.CertificateValidation += ConfigurationOptions_CertificateValidation;
     ConnectionPool = new RedisCacheConnectionPoolManager(this.config);
     Client         = new RedisCacheClient(ConnectionPool, new Utf8JsonSerializer(), config);
     RedisDb        = Client.GetDbFromConfiguration();
     Db             = RedisDb.Database;
 }
Example #26
0
        private static IRedisCacheClient GetCacheClient(RedisConfiguration redisConfig, ISerializer sz = null)
        {
            var poolManager = new RedisCacheConnectionPoolManager(redisConfig);

            if (sz == null)
            {
                sz = new MsgPackObjectSerializer();
            }
            var cacheClient = new RedisCacheClient(poolManager, sz, redisConfig);

            return(cacheClient);
        }
Example #27
0
        public async Task <ActionResult> Edit([Bind(Include = "VeiculoId,Carro,Marca,Ano,Placa")] Veiculo veiculo)
        {
            if (ModelState.IsValid)
            {
                db.Entry(veiculo).State = EntityState.Modified;
                await db.SaveChangesAsync();

                await RedisCacheClient.ReplaceAsync("Veiculo:" + veiculo.VeiculoId, veiculo, new TimeSpan(0, 10, 0));

                return(RedirectToAction("Index"));
            }
            return(View(veiculo));
        }
Example #28
0
        public async Task <ActionResult> Edit([Bind(Include = "CategoriaId,Nome")] Categoria categoria)
        {
            if (ModelState.IsValid)
            {
                db.Entry(categoria).State = EntityState.Modified;
                await db.SaveChangesAsync();

                await RedisCacheClient.ReplaceAsync("Categoria:" + categoria.CategoriaId, categoria, new TimeSpan(0, 10, 0));

                return(RedirectToAction("Index"));
            }
            return(View(categoria));
        }
Example #29
0
        public async Task <ActionResult> Edit([Bind(Include = "ContatoId,Nome,Email")] Contato contato)
        {
            if (ModelState.IsValid)
            {
                db.Entry(contato).State = EntityState.Modified;
                await db.SaveChangesAsync();

                await RedisCacheClient.ReplaceAsync("Contato:" + contato.ContatoId, contato, new TimeSpan(0, 10, 0));

                return(RedirectToAction("Index"));
            }
            return(View(contato));
        }
Example #30
0
        static void Main(string[] args)
        {

            MallCard mall = new MallCard()
            {
                ID = Guid.NewGuid().ToString("N"),
                MallID = new Random().Next(1, 100),
                UID = new Random().Next(1, 1000)
            };


            int seed = 1;
            Stopwatch sw = new Stopwatch();
            Task[] taskList = new Task[seed];
            string conStr = System.Configuration.ConfigurationManager.AppSettings["conStr"];

            using (RedisCacheClient client = new RedisCacheClient(conStr, 2))
            {
                sw.Restart();

                string key = "123ABC";
                taskList[0] = client.SetAsync<string>(key, "33333");

                //for (var i = 0; i < seed; i++)
                //{
                //    //RedisKey key = "MallCardbcb0878b8e814b8fa7540862729044c9"; //mall.GetKey();
                //    ////RedisValue val = serializer.Serialize(mall);
                //    client.Database.StringSet(key, val);

                //    //var task = client.Database.StringGetAsync(key).ContinueWith(x =>
                //    //{
                //    //    var mall2 = serializer.Deserialize<MallCard2>(x.Result);
                //    //    ;
                //    //});
                //    //taskList[i] = task;

                //    //client.s

                //    string key = "123ABC";
                //    taskList[i] = client.GetAsync<MallCard2>(key);
                //}

                Task.WhenAll(taskList);
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds);
                Console.WriteLine(seed / sw.Elapsed.TotalSeconds);
                Console.ReadLine();
                //Assert.AreEqual(mall.MallID, mall2.MallID);
            }

        }
Example #31
0
 public void Publish()
 {
     MallCard mall = new MallCard()
     {
         ID = Guid.NewGuid().ToString("N").Substring(0, 5),
         Name = Guid.NewGuid().ToString("N"),
         MallID = new Random().Next(1, 100),
         UID = new Random().Next(1, 1000)
     };
     using (RedisCacheClient client = new RedisCacheClient(serializer))
     {
         client.Publish("var", mall);
     }
 }
Example #32
0
        static void Main(string[] args)
        {
            using (RedisCacheClient client = new RedisCacheClient())
            {
                client.Subscribe<MallCard>("var", (x) =>
                {
                    Console.WriteLine(x.Name);
                });

                Console.ReadLine();
            }

            Console.WriteLine("over...");
        }
Example #33
0
        public void StringSet_StringGet()
        {
            MallCard mall = new MallCard()
            {
                ID = Guid.NewGuid().ToString("N").Substring(0, 5),
                Name = Guid.NewGuid().ToString("N"),
                MallID = new Random().Next(1, 100),
                UID = new Random().Next(1, 1000)
            };
            using (RedisCacheClient client = new RedisCacheClient(serializer))
            {
                var key = mall.GetKey();
                RedisValue val = serializer.Serialize(mall);
                client.Database.StringSet(key, val);
                client.Set(key, mall);

                //byte[] val2 = client.Database.StringGet(key);
                //var mall2 = serializer.Deserialize<MallCard2>(val2);
                var mall2 = client.Get<MallCard2>(key);

                Assert.AreEqual(mall.Name, mall2.Name);
            }
        }
Example #34
0
 public RedisTableCache(RedisCacheClient client)
     : base(client)
 {
 }
Example #35
0
 public RedisLockTests() {
     var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());
     _cacheClient = new RedisCacheClient(muxer.GetDatabase());
     _locker = new CacheLockProvider(_cacheClient);
 }
Example #36
-1
        public RedisQueue(RedisQueueOptions <T> options) : base(options)
        {
            if (options.ConnectionMultiplexer == null)
            {
                throw new ArgumentException("ConnectionMultiplexer is required.");
            }

            options.ConnectionMultiplexer.ConnectionRestored += ConnectionMultiplexerOnConnectionRestored;
            _cache = new RedisCacheClient(new RedisCacheClientOptions {
                ConnectionMultiplexer = options.ConnectionMultiplexer, Serializer = _serializer
            });

            _payloadTimeToLive = GetPayloadTtl();
            _subscriber        = _options.ConnectionMultiplexer.GetSubscriber();

            string listPrefix = _options.ConnectionMultiplexer.IsCluster() ? "{q:" + _options.Name + "}" : $"q:{_options.Name}";

            _queueListName = $"{listPrefix}:in";
            _workListName  = $"{listPrefix}:work";
            _waitListName  = $"{listPrefix}:wait";
            _deadListName  = $"{listPrefix}:dead";

            // min is 1 second, max is 1 minute
            var interval = _options.WorkItemTimeout > TimeSpan.FromSeconds(1) ? _options.WorkItemTimeout.Min(TimeSpan.FromMinutes(1)) : TimeSpan.FromSeconds(1);

            _maintenanceLockProvider = new ThrottlingLockProvider(_cache, 1, interval);

            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace("Queue {QueueId} created. Retries: {Retries} Retry Delay: {RetryDelay:g}, Maintenance Interval: {MaintenanceInterval:g}", QueueId, _options.Retries, _options.RetryDelay, interval);
            }
        }
        public RedisCacheClientTests() {
            //if (!Settings.Current.UseAzureCache)
            //    return;

            var muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString());
            _cache = new RedisCacheClient(muxer.GetDatabase());
        }