Ejemplo n.º 1
0
        public void Test_Set()
        {
            typedCache.Set("Test_Set", new User(), TimeSpan.FromSeconds(30));

            var resultFromCache = typedCache.Get <User>("Test_Set");

            Assert.NotNull(resultFromCache);
        }
Ejemplo n.º 2
0
        public async Task <IEnumerable <Filme> > GetFilmesAsync(
            Pesquisa pesquisa, string idioma)
        {
            try
            {
                var cacheKey = $"filmes::{pesquisa.TermoPesquisa}::" +
                               $"{pesquisa.AnoLancamento}::{idioma}";

                if (!typedCache.TryGet(cacheKey,
                                       out TmdbSearchMoviesGetResult tmdbSearchMoviesGetResult))
                {
                    var tmdbSearchMoviesGet =
                        mapper.Map <TmdbSearchMoviesGet>(pesquisa);

                    tmdbSearchMoviesGet.ApiKey =
                        tmdbAdapterConfiguration.TmdbApiKey;

                    tmdbSearchMoviesGet.Language = idioma;

                    tmdbSearchMoviesGetResult = await tmdbApi
                                                .SearchMovies(tmdbSearchMoviesGet);

                    typedCache.Set(cacheKey, tmdbSearchMoviesGetResult,
                                   TimeSpan
                                   .FromSeconds(
                                       tmdbAdapterConfiguration
                                       .TempoDeCacheDaPesquisaEmSegundos));
                }

                return(mapper
                       .Map <IEnumerable <Filme> >(tmdbSearchMoviesGetResult.Results));
            }
            catch (ApiException e)
            {
                switch (e.StatusCode)
                {
                case (HttpStatusCode)429:     // TooManyRequests
                    throw new BuscarFilmesCoreException(
                              BuscarFilmesCoreError.LimiteDeRequisicoesAtingido);
                }

                // Qualquer outro codigo de retorno esta sendo considerado como
                // uma situacao nao prevista.  A excecao sera relancada e caso
                // nao tratada, acarretara em um erro interno.
                // Obs.: Deixar essa excecao sem tratamento, a principio nao eh
                // errado, pois eh uma condicao nao prevista, ou seja,
                // desconhecida. Como este projeto implementa um ponto central
                // de tratamento de erros (por meio das bibliotecas
                // Otc.ExceptionHandler e Otc.Mvc.Filters) este erro sera
                // devidamente registrado (logs) e um identificador do registro
                // sera fornecido na resposta. Note que em ambientes de
                // desenvolvimento, (variavel de ambiente ASPNETCORE_ENVIRONMENT
                // definida como Development) a excecao sera exposta na resposta,
                // no entanto, em ambientes produtivos,
                // apenas o identificador do log do erro sera fornecido.
                throw;
            }
        }
Ejemplo n.º 3
0
        public async Task <IEnumerable <Filme> > GetFilmesAsync(Pesquisa pesquisa)
        {
            var cacheKey = $"filmes::{pesquisa.TermoPesquisa}::{pesquisa.AnoLancamento}";

            if (!typedCache.TryGet(cacheKey, out IEnumerable <TmdbMoviesDto> tmdbMovies))
            {
                var query = @"SELECT Id, Title, Overview, ReleaseDate 
                            FROM Tmdb 
                            WHERE Title like @TermoPesquisa
                                AND ReleaseDate = @AnoLancamento";

                var parametros = new DynamicParameters();

                parametros.Add("TermoPesquisa", $"%{pesquisa.TermoPesquisa}%");
                parametros.Add("AnoLancamento", pesquisa.AnoLancamento);

                tmdbMovies = await dbConnection.QueryAsync <TmdbMoviesDto>(query);

                typedCache.Set(cacheKey, tmdbMovies, TimeSpan.FromSeconds(sqlAdapterConfiguration.SegundosValidadeCacheParametro));
            }

            var filmes = Mapper.Map <IEnumerable <Filme> >(tmdbMovies);

            return(filmes);
        }
Ejemplo n.º 4
0
        public void Simple_Get_Set_Test()
        {
            _cache.GetOrDefault("A").ShouldBe(null);
            _cache.Set("A", new MyCacheItem {
                Value = 42
            });
            _cache.GetOrDefault("A").ShouldNotBe(null);
            _cache.GetOrDefault("A").Value.ShouldBe(42);

            _cache.Get("B", () => new MyCacheItem {
                Value = 43
            }).Value.ShouldBe(43);
            _cache.Get("B", () => new MyCacheItem {
                Value = 44
            }).Value.ShouldBe(43);                                                    //不调用工厂,所以值不变

            var items1 = _cache.GetOrDefault(new string[] { "B", "C" });

            items1[0].Value.ShouldBe(43);
            items1[1].ShouldBeNull();

            var items2 = _cache.GetOrDefault(new string[] { "C", "D" });

            items2[0].ShouldBeNull();
            items2[1].ShouldBeNull();

            _cache.Set(new KeyValuePair <string, MyCacheItem>[] {
                new KeyValuePair <string, MyCacheItem>("C", new MyCacheItem {
                    Value = 44
                }),
                new KeyValuePair <string, MyCacheItem>("D", new MyCacheItem {
                    Value = 45
                })
            });

            var items3 = _cache.GetOrDefault(new string[] { "C", "D" });

            items3[0].Value.ShouldBe(44);
            items3[1].Value.ShouldBe(45);

            var items4 = _cache.Get(new string[] { "D", "E" }, (key) => new MyCacheItem {
                Value = key == "D" ? 46 : 47
            });

            items4[0].Value.ShouldBe(45); //不调用工厂,所以值不变
            items4[1].Value.ShouldBe(47);
        }
 public void SetFile(string token, byte[] content)
 {
     _cache.Set(token, new TempFileInfo(content), TimeSpan.FromMinutes(1)); // expire time is 1 min by default
 }
Ejemplo n.º 6
0
 public void InitCache()
 {
     using (var unitOfWork = _unitOfWorkManager.Begin())
     {
         List <ProductClassCacheDto> pcSet = this._productClassRepository.GetAll().Include(p => p.ProductSortBy).ToList().Select(o => new ProductClassCacheDto()
         {
             ProductClassId = o.Id,
             ProductSortId  = o.ProductSortId,
             SortName       = o.ProductSortBy.SortName,
             ClassName      = o.ClassName,
             PTId           = o.PTId,
             PostTaxRate    = o.PostTaxRate,
             BCTaxRate      = o.BCTaxRate,
             IsActive       = o.IsActive
         }).ToList();
         productClassCache.Set("host", pcSet);
         var logisticQuery = this._logisticRepository.GetAll().Include(p => p.LogisticChannels)
                             .ThenInclude((LogisticChannel p) => p.NumFreights)
                             .Include(p => p.LogisticChannels).ThenInclude((LogisticChannel p) => p.WeightFreights)
                             .Include(p => p.LogisticChannels).ThenInclude((LogisticChannel p) => p.SplitRules).ThenInclude((SplitRule p) => p.ProductClasses);
         var logisticRelatedQuery = this._logisticRelatedRepository.GetAll().Include(p => p.Items).ThenInclude((LogisticRelatedItem p) => p.LogisticBy);
         var hostLogistics        = logisticQuery.IgnoreQueryFilters().Where(o => o.TenantId == null && o.IsActive).Select(this._objectMapper.Map <LogisticCacheDto>).ToList();
         splitPackageSettingCache.Set("host", new SplitPackageSettingCache()
         {
             OwnLogistics = hostLogistics,
             Relateds     = logisticRelatedQuery.IgnoreQueryFilters().Where(o => o.TenantId == null).Select(this._objectMapper.Map <LogisticRelatedCacheDto>).ToList()
         });
         foreach (var item in _tenantRepository.GetAll().Where(o => o.IsActive).ToList())
         {
             var ownLogistics = logisticQuery.IgnoreQueryFilters().Where(o => o.TenantId == item.Id && o.IsActive).Select(this._objectMapper.Map <LogisticCacheDto>).ToList();
             var import       = this._importLogisticRepository.GetAll().Include(o => o.LogisticChannelBy)
                                .ThenInclude((LogisticChannel p) => p.LogisticBy)
                                .IgnoreQueryFilters().Where(o => o.TenantId == item.Id).ToList();
             var set = hostLogistics.Where(o => import.Any(oi => oi.LogisticChannelBy.LogisticId == o.Id)).SelectMany(o => o.LogisticChannels)
                       .Where(o => import.Any(oi => oi.LogisticChannelId == o.Id)).ToList();
             var importChannls = new ChannelCacheDto[set.Count];
             set.CopyTo(importChannls);
             var importSet = import.GroupBy(o => o.LogisticChannelBy.LogisticBy).Select(o => {
                 var result = new LogisticCacheDto()
                 {
                     Id = o.Key.Id,
                     CorporationName = o.Key.CorporationName,
                     CorporationUrl  = o.Key.CorporationUrl,
                     LogoURL         = o.Key.LogoURL,
                     LogisticCode    = o.Key.LogisticCode,
                 };
                 result.LogisticChannels = o.Select(oi => {
                     var c = importChannls.Where(oii => oi.LogisticChannelId == oii.Id).FirstOrDefault();
                     if (c == null)
                     {
                         return(null);
                     }
                     if (!string.IsNullOrEmpty(oi.AliasName))
                     {
                         c.AliasName = oi.AliasName;
                     }
                     if (oi.Way.HasValue)
                     {
                         c.Way = oi.Way.Value;
                     }
                     var information = oi.GetInformation();
                     if (information != null)
                     {
                         c.WeightFreights = information.WeightChargeRules.Select(this._objectMapper.Map <WeightFreightCacheDto>).ToList();
                         c.NumFreights    = information.NumChargeRules.Select(this._objectMapper.Map <NumFreightCacheDto>).ToList();
                     }
                     return(c);
                 }).Where(oi => oi != null).ToList();
                 return(result);
             });
             ownLogistics.AddRange(importSet);
             var relateds = logisticRelatedQuery.IgnoreQueryFilters().Where(o => o.TenantId == item.Id).Select(this._objectMapper.Map <LogisticRelatedCacheDto>).ToList();
             if (ownLogistics.Count > 0)
             {
                 splitPackageSettingCache.Set(item.Id.ToString(), new SplitPackageSettingCache()
                 {
                     OwnLogistics = ownLogistics,
                     Relateds     = relateds
                 });
             }
         }
         unitOfWork.Complete();
     }
 }