Пример #1
0
        public async Task <T> GetAsync <T>(string name)
        {
            var instanceData = await _distributedCache?.GetAsync(name);

            if (instanceData != null && instanceData.Length > 0)
            {
                return(DeserializeFromCache <T>(instanceData));
            }
            return(default(T));
        }
        public async Task <IList <IServiceInstance> > GetAsync(string name)
        {
            var instanceData = await _distributedCache?.GetAsync(name);

            if (instanceData != null && instanceData.Length > 0)
            {
                return(DeserializeFromCache <List <SerializableIServiceInstance> >(instanceData).ToList <IServiceInstance>());
            }
            return(null);
        }
        public async Task <ConcurrentObject> TryGetValueAsync(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var bytes = await _distributedCache.GetAsync(key.ToString());

            if (bytes == null)
            {
                return(null);
            }

            var serialized = Encoding.UTF8.GetString(bytes);

            return(JsonConvert.DeserializeObject <ConcurrentObject>(serialized));
        }
        /// <summary>
        /// 异步获取指定键的缓存项,不存在则从指定委托获取,并回存到缓存中再返回
        /// </summary>
        public static async Task <TResult> GetAsync <TResult>(this IDistributedCache cache, string key, Func <Task <TResult> > getAsyncFunc, DistributedCacheEntryOptions options = null)
        {
            TResult result = await cache.GetAsync <TResult>(key);

            if (!Equals(result, default(TResult)))
            {
                return(result);
            }
            result = await getAsyncFunc();

            if (Equals(result, default(TResult)))
            {
                return(default(TResult));
            }
            await cache.SetAsync(key, result, options);

            return(result);
        }
Пример #5
0
        public async Task <T> GetAsync <T>(string key)
        {
            if (!_scopedCache.TryGetValue(key, out var value))
            {
                var data = await _distributedCache.GetAsync(key);

                if (data == null)
                {
                    return(default(T));
                }

                value = Deserialize <T>(data);

                _scopedCache[key] = value;
            }

            return((T)value);
        }
Пример #6
0
        public async Task Invoke(HttpContext httpContext)
        {
            var token = await httpContext.GetTokenAsync("access_token");

            if (!string.IsNullOrEmpty(token))
            {
                var cachedUserInfo = await _cache.GetAsync(token);

                if (cachedUserInfo != null)
                {
                    var claims = JsonConvert.DeserializeObject <List <string> >(Encoding.UTF8.GetString(cachedUserInfo));
                    httpContext.Items["UserClaims"] = claims;
                }
                else
                {
                    var client = new HttpClient();

                    var response = await client.GetUserInfoAsync(new UserInfoRequest
                    {
                        Address = ConfigurationHelper.Instance.UserInfoEndpoint,
                        Token   = token
                    });

                    if (response.IsError)
                    {
                        throw new Exception(response.Error);
                    }

                    var claims = response.Claims.Where(c => c.Type == "entitlement_group").Select(c => c.Value).ToList();

                    var options = new DistributedCacheEntryOptions()
                                  .SetSlidingExpiration(TimeSpan.FromMinutes(15));

                    var    output            = JsonConvert.SerializeObject(claims, Formatting.Indented);
                    byte[] encodedUserClaims = Encoding.UTF8.GetBytes(output);

                    await _cache.SetAsync(token, encodedUserClaims, options);

                    httpContext.Items["UserClaims"] = claims;
                }
            }

            await _next(httpContext);
        }
Пример #7
0
        public async Task <List <Card> > GetAsync(string heroName)
        {
            List <Card> cardList;
            string      jsonValue;
            // Önce Redis üzerinde gelen heroName key ile bir value var mı bakalım
            var cards = await _distributedCache.GetAsync(heroName);

            if (cards == null) // Redis'te yoksa cache'e al
            {
                _logger.LogWarning($"{DateTime.Now.ToLongTimeString()} -> Redis'te yoktu. O zaman önce oraya ekleyelim");

                // Önce diğer servisten kahramana göre kartları isteyelim
                var resp = await _client.GetAsync($"http://localhost:5005/api/card/{heroName}");

                // HTTP Get çağrısına dönecek JSON içeriği Card listesine çevirelim
                var stream = await resp.Content.ReadAsStringAsync();

                _logger.LogWarning($"Diğer servisten gelen içerik\n{stream}");

                cardList = JsonConvert.DeserializeObject <List <Card> >(stream);
                // Diğer servisten gelen json içeriği redis'te tutmak için UTF8 tipinden binary formata dönüştürelim.
                cards = Encoding.UTF8.GetBytes(stream);

                // Cache üzerinde saklama ayarları
                var options = new DistributedCacheEntryOptions()
                              .SetSlidingExpiration(TimeSpan.FromMinutes(5))    // Test amaçlı olarak 5 dakika erişilmediyse expire olacak
                              .SetAbsoluteExpiration(DateTime.Now.AddHours(1)); // Her durumda saatte bir expire edecek

                // key değeri kahramanın adı. İçerik cards değişkenin binary değeri(Kuvvetle muhtemel List<Card> içeriği).
                // Seçenekler 5 dakika boyunca erişilmezse düşür ve her durumda saat başı yenile
                await _distributedCache.SetAsync(heroName, cards, options);
            }
            else // Redis'te varsa
            {
                _logger.LogWarning($"{DateTime.Now.ToLongTimeString()} -> Redis'te vermış. Oradan çekelim :)");

                // nesneyi UTF8 string'e çözümle
                jsonValue = Encoding.UTF8.GetString(cards);
                // şimdi güzelim Newtonsoft ile onu Card listesine dönüştür
                cardList = JsonConvert.DeserializeObject <List <Card> >(jsonValue);
            }

            return(cardList);
        }
Пример #8
0
        public async Task JoinParty(string partyName, PlayerModel player)
        {
            // set initial id of player
            player.ConnectionID = Context.ConnectionId;

            //update ConnectionId:Partyname index
            var success = await AddToIndex(partyName);

            // look for party
            var party = await _cache.GetAsync <PartyModel>($"party:{partyName}");

            if (party == null)
            {
                party = new PartyModel()
                {
                    Name = partyName, Players = new List <PlayerModel> {
                        player
                    }
                };
                await _cache.SetAsync <PartyModel>($"party:{partyName}", party);

                await Clients.Caller.SendAsync("EnteredParty", party, player);
            }
            else
            {
                var oldPlayer = party.Players.FirstOrDefault(x => x.Character.Name == player.Character.Name || x.ConnectionID == player.ConnectionID);

                if (oldPlayer == null)
                {
                    party.Players.Insert(0, player);
                }
                else
                {
                    // index of old player
                    var index = party.Players.IndexOf(oldPlayer);
                    await Groups.RemoveFromGroupAsync(oldPlayer.ConnectionID, partyName);

                    party.Players[index] = player;
                }

                await _cache.SetAsync <PartyModel>($"party:{partyName}", party);

                await Clients.Caller.SendAsync("EnteredParty", party, player);
            }

            await Groups.AddToGroupAsync(Context.ConnectionId, partyName);

            await Clients.OthersInGroup(partyName).SendAsync("PlayerJoined", player);

            await Clients.Group(partyName).SendAsync("PlayerUpdated", player);
        }
Пример #9
0
        /// <summary>
        /// Returns a list of blog posts.
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        /// <remarks>
        /// For the blog index page, admin post page, main rss feed.
        /// </remarks>
        public async Task <BlogPostList> GetListAsync(int pageIndex, int pageSize, bool cacheable = true)
        {
            PostListQuery query = new PostListQuery(EPostListQueryType.BlogPosts)
            {
                PageIndex = (pageIndex <= 0) ? 1 : pageIndex,
                PageSize  = pageSize,
            };

            // cache only first page of the public site, not admin or rss
            if (query.PageIndex == 1 && cacheable)
            {
                return(await _cache.GetAsync(BlogCache.KEY_POSTS_INDEX, BlogCache.Time_PostsIndex, async() =>
                {
                    return await QueryPostsAsync(query);
                }));
            }

            return(await QueryPostsAsync(query));
        }
Пример #10
0
        public async Task <T> GetAsync <T>(string key, CancellationToken cancellationToken = default,
                                           Func <Task <T> > valueGetter = default, TimeSpan?absoluteExpiration = default)
        {
            _logger.Debug($"Getting from cache... Key: {key}");
            var byteArray = await _distributedCache.GetAsync(key, cancellationToken);

            var cacheValue = _serializer.FromByteArray <T>(byteArray);

            if (EqualityComparer <T> .Default.Equals(cacheValue, default) && valueGetter != null)
            {
                _logger.Debug("Invoking valueGetter...");
                cacheValue = await valueGetter();
                await SetAsync(key, cacheValue, cancellationToken, absoluteExpiration);

                return(cacheValue);
            }

            return(cacheValue);
        }
Пример #11
0
        public async Task <PictureOfDay> GetPictureOfDay()
        {
            var cache = await _distributedCache.GetAsync(key);

            if (cache != null)
            {
                return(_objService.GetObjectCache(cache));
            }
            else
            {
                var cacheExpiration = (DateTime.Today.AddDays(1).AddTicks(-1) - DateTime.Now).TotalSeconds;
                var pictureOfDay    = await _apiService.GetPictureOfDay();

                await _distributedCache.SetAsync(key, _objService.SetObjectCache(pictureOfDay),
                                                 new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(cacheExpiration)));

                return(pictureOfDay);
            }
        }
        private async Task AssertGetCacheItemFromDatabaseAsync(
            IDistributedCache cache,
            string key,
            byte[] expectedValue,
            TimeSpan?slidingExpiration,
            DateTimeOffset?absoluteExpiration,
            DateTimeOffset expectedExpirationTime)
        {
            var value = await cache.GetAsync(key);

            Assert.NotNull(value);
            Assert.Equal(expectedValue, value);
            var cacheItemInfo = await GetCacheItemFromDatabaseAsync(key);

            Assert.NotNull(cacheItemInfo);
            Assert.Equal(slidingExpiration, cacheItemInfo.SlidingExpirationInSeconds);
            Assert.Equal(absoluteExpiration, cacheItemInfo.AbsoluteExpiration);
            Assert.Equal(expectedExpirationTime, cacheItemInfo.ExpiresAtTime);
        }
        public static async Task <TObjectType> Get <TObjectType>(this IDistributedCache cache, string key)
            where TObjectType : class, new()
        {
            var cachedItemBytes = await cache.GetAsync(key);

            if (cachedItemBytes == null)
            {
                return(null);
            }

            var value = DecodeObject(cachedItemBytes);

            if (typeof(TObjectType) == typeof(string))
            {
                return(value as TObjectType);
            }

            return(JsonConvert.DeserializeObject <TObjectType>(value));
        }
        public virtual async Task <bool> ValidateAsync(string codeCacheKey, string verificationCode,
                                                       VerificationCodeConfiguration configuration)
        {
            var cacheItem = await _cache.GetAsync(codeCacheKey, true);

            if (cacheItem == null)
            {
                return(false);
            }

            var result = IsInputCodeCorrect(verificationCode, cacheItem.Code, configuration);

            if (result)
            {
                await _cache.RemoveAsync(codeCacheKey);
            }

            return(result);
        }
Пример #15
0
        public override async Task <T> GetByIdAsync(int id, string?namedOption = null, CancellationToken cancellationToken = default)
        {
            var key = $"{TableName}-{id}";

            var cachedItem = await _cache.GetAsync <T>(key, cancellationToken);

            if (cachedItem != null)
            {
                return(cachedItem);
            }

            var result = await base.GetByIdAsync(id, namedOption, cancellationToken);

            var options = _optionsMonitor.Get(namedOption);

            await _cache.SetAsync <T>(key, result, options.CacheOptions, cancellationToken);

            return(result);
        }
Пример #16
0
        public static async Task <T> GetAsync <T>(this IDistributedCache distributedCache, string name, CancellationToken token = default(CancellationToken))
        {
            T   ret        = default(T);
            var serializer = new XmlSerializer(typeof(T));

            using (var stream = new MemoryStream())
            {
                var bytes = await distributedCache.GetAsync(name, token);

                if (bytes != null)
                {
                    await stream.WriteAsync(bytes, 0, bytes.Length);

                    stream.Position = 0;
                    ret             = (T)serializer.Deserialize(stream);
                }
            }
            return(ret);
        }
Пример #17
0
        public async Task <List <AuthClaim>?> GetClaimsByAuthCodeAsync(string authCode)
        {
            if (string.IsNullOrWhiteSpace(authCode))
            {
                throw new ArgumentException(nameof(authCode));
            }

            List <AuthClaim>?result = null;

            var encodedAuthClaimList = await _Cache.GetAsync(authCode);

            if (encodedAuthClaimList != null)
            {
                var claimListJson = Encoding.UTF8.GetString(encodedAuthClaimList);
                result = JsonConvert.DeserializeObject <List <AuthClaim> >(claimListJson);
            }

            return(result);
        }
        public async Task <TreeNode <NavigationNode> > GetTree()
        {
            // ultimately we will need to cache sitemap per site
            // we will implement a custom ICacheKeyResolver to resolve multi tenant cache keys

            if (rootNode == null)
            {
                log.LogDebug("rootnode was null so checking distributed cache");
                string cacheKey = cacheKeyResolver.ResolveCacheKey(options.CacheKey);

                NavigationTreeXmlConverter converter = new NavigationTreeXmlConverter();

                await cache.ConnectAsync();

                byte[] bytes = await cache.GetAsync(cacheKey);

                if (bytes != null)
                {
                    log.LogDebug("rootnode was found in distributed cache so deserializing");
                    string    xml = Encoding.UTF8.GetString(bytes);
                    XDocument doc = XDocument.Parse(xml);

                    rootNode = converter.FromXml(doc);
                }
                else
                {
                    log.LogDebug("rootnode was not in cache so building");

                    rootNode = await implementation.GetTree();

                    string xml2 = converter.ToXmlString(rootNode);

                    await cache.SetAsync(
                        cacheKey,
                        Encoding.UTF8.GetBytes(xml2),
                        new DistributedCacheEntryOptions().SetSlidingExpiration(
                            TimeSpan.FromSeconds(options.CacheDurationInSeconds))
                        );
                }
            }

            return(rootNode);
        }
        public async Task <GetWeatherByLocationQueryResponse> Handle(GetWeatherByLocationParameters request, CancellationToken cancellationToken)
        {
            const string version = "v1";

            var cache = await _distributedCache.GetAsync(request.CreateCacheKey(), cancellationToken);

            if (cache != null)
            {
                var cacheText = Encoding.UTF8.GetString(cache);
                var cacheData = JsonSerializer.Deserialize <WeatherByLocation>(cacheText);

                return(new GetWeatherByLocationQueryResponse
                {
                    Data = cacheData,
                    Source = "Cache",
                    Version = version
                });
            }

            var client = _httpClientFactory.CreateClient(nameof(GetWeatherByLocationQuery));

            var url = $"weather?q={request.City}&appid={_configuration["OpenWeatherMap:ApiKey"]}&lang={request.Language ?? "de"}&units={request.Units ?? "metric"}";
            var xx  = await client.GetAsync(url, cancellationToken);

            var json = await xx.Content.ReadAsStringAsync();

            var data = JsonSerializer.Deserialize <WeatherByLocation>(json);

            var response = new GetWeatherByLocationQueryResponse
            {
                Data    = data,
                Source  = "Live",
                Version = version
            };

            await _distributedCache.SetAsync(
                request.CreateCacheKey(),
                Encoding.UTF8.GetBytes(json),
                new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(1)),
                cancellationToken);

            return(response);
        }
Пример #20
0
        public async Task<ActionResult<string>> GetTheTime()
        {
            var time = await Cache.GetAsync("time");
            string newTime = null;
            if(time == null) // it wasn't in the cache. never was, or was removed after it expired
            {
                newTime = DateTime.Now.ToLongTimeString();
                var encodedTime = Encoding.UTF8.GetBytes(newTime);
                var options = new DistributedCacheEntryOptions()
                    .SetAbsoluteExpiration(DateTime.Now.AddSeconds(15));
                await Cache.SetAsync("time", encodedTime, options);
            }
            else
            {
                newTime = Encoding.UTF8.GetString(time);
            }

            return Ok($"It is now {newTime}");
        }
Пример #21
0
        private async Task <TResponse> GetFromDistrubutedCache(ICacheable cacheable, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next)
        {
            var value = await _distributedCache.GetAsync(cacheable.CacheSettings.Key, cancellationToken);

            if (value != null)
            {
                return(_serializer.Deserialize <TResponse>(value));
            }
            var response = await next();

            var option = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = cacheable.CacheSettings.Value,
                SlidingExpiration = TimeSpan.FromMinutes(30)
            };
            await _distributedCache.SetAsync(cacheable.CacheSettings.Key, _serializer.Serialize(response), option, cancellationToken);

            return(response);
        }
        public async Task <Response <InvestmentsResponse> > Handle(InvestmentsRequest request, CancellationToken cancellationToken)
        {
            var responseCache = await _cache.GetAsync(CacheKeys.Portfolio, cancellationToken);

            if (responseCache is null)
            {
                _tracer.ActiveSpan.SetTag("cache", false);
                var investmentResponse = await _portfolio.GetAsync();

                _ = _cache.SetAsync(CacheKeys.Portfolio, JsonSerializer.SerializeToUtf8Bytes(investmentResponse), DateTime.Now.UntilMidnight(), cancellationToken);
                return(new Response <InvestmentsResponse>(investmentResponse));
            }
            else
            {
                _tracer.ActiveSpan.SetTag("cache", true);
                var investmentResponse = JsonSerializer.Deserialize <InvestmentsResponse>(new ReadOnlySpan <byte>(responseCache));
                return(new Response <InvestmentsResponse>(investmentResponse));
            }
        }
Пример #23
0
        public async Task Cache_Should_Invalidator_WhenFeatureChanged()
        {
            // Arrange cache feature.
            await _featureManagementStore.GetOrNullAsync(TestFeatureDefinitionProvider.SocialLogins,
                                                         EditionFeatureValueProvider.ProviderName,
                                                         TestEditionIds.Regular.ToString("N"));

            var feature = await _featureValueRepository.FindAsync(TestFeatureDefinitionProvider.SocialLogins,
                                                                  EditionFeatureValueProvider.ProviderName,
                                                                  TestEditionIds.Regular.ToString("N"));

            // Act
            await _featureValueRepository.DeleteAsync(feature);

            // Assert
            (await _cache.GetAsync(FeatureValueCacheItem.CalculateCacheKey(TestFeatureDefinitionProvider.SocialLogins,
                                                                           EditionFeatureValueProvider.ProviderName,
                                                                           TestEditionIds.Regular.ToString("N")))).ShouldBeNull();
        }
        public static async Task <byte[]?> GetOrSetAsync(this IDistributedCache cache, string key, Func <Task <byte[]?> > valueFactory,
                                                         DistributedCacheEntryOptions options, CancellationToken token = default)
        {
            var cached = await cache.GetAsync(key, token);

            if (cached != null)
            {
                return(cached);
            }

            var value = await valueFactory();

            if (value != null)
            {
                await cache.SetAsync(key, value, options, token);
            }

            return(value);
        }
 public static async Task <byte[]> GetAsync(string key)
 {
     try
     {
         if (_cacheEnable)
         {
             return(await _distributedCache?.GetAsync(key));
         }
         else
         {
             return(null);
         }
     }
     catch (Exception ex)
     {
         LogManager.Error(ex.Message);
         return(null);
     }
 }
Пример #26
0
        public async Task <OnCallDeveloperResponse> GetDeveloper()
        {
            //await Task.Delay(3000); // wait three seconds to simulate a slow api call.

            //return new OnCallDeveloperResponse
            //{
            //    Email = "*****@*****.**"
            //};

            // 1. Ask the cache for the email.
            var storedEmail = await Cache.GetAsync("email");

            string emailAddress = null;

            // 2. If it isn't in the cache
            if (storedEmail == null)    // not in the cache.  Cache me outside
            {
                await Task.Delay(3000); // wait three seconds to simulate a slow api call.

                // after you get it from the remote api, pop it in the cache.
                var emailToSave  = $"bob-{DateTime.Now.ToLongTimeString()}@aol.com";
                var encodedEmail = Encoding.UTF8.GetBytes(emailToSave);

                // set up the options on storing the thing.
                var options = new DistributedCacheEntryOptions()
                              .SetAbsoluteExpiration(DateTime.Now.AddSeconds(15));

                // store the sucker
                await Cache.SetAsync("email", encodedEmail, options);

                emailAddress = emailToSave;
            }
            else
            {
                // Cache hit!  It was there.  Just decode it to a string.
                emailAddress = Encoding.UTF8.GetString(storedEmail);
            }

            return(new OnCallDeveloperResponse
            {
                Email = emailAddress
            });
        }
Пример #27
0
        /// <summary>
        /// 获取可用AccessTokenResult对象
        /// </summary>
        /// <param name="getNewToken">是否强制重新获取新的Token</param>
        /// <returns></returns>
        public async Task <AccessTokenResult> GetAccessTokenResult(bool getNewToken = false)
        {
            var accessToken = await _cache.GetAsync(AppId);

            if (accessToken == null || getNewToken == true || accessToken.expires_in < DateTime.Now.Second)
            {
                accessToken = await GetTokenAsync();

                _ = _cache.SetAsync(AppId, accessToken, new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(accessToken.expires_in)
                });
                return(accessToken);
            }
            else
            {
                return(accessToken);
            }
        }
Пример #28
0
        public async Task <ChatState> GetChatStateAsync(bool clearState = false)
        {
            var chatStateBytes = await _cache.GetAsync(CacheKey);

            if (chatStateBytes == null)
            {
                return(new ChatState());
            }

            var chatStateString = Encoding.ASCII.GetString(chatStateBytes);
            var chatState       = new ChatState
            {
                WaitingFor = chatStateString
            };

            await _cache.RemoveAsync(CacheKey);

            return(chatState);
        }
Пример #29
0
        public static async Task <T> GetAsync <T>(this IDistributedCache cache, string key)
        {
            var val = await cache.GetAsync(key);

            var result = default(T);

            if (val == null)
            {
                return(result);
            }

            using (var memoryStream = new MemoryStream(val))
            {
                var binaryFormatter = new BinaryFormatter();
                result = (T)binaryFormatter.Deserialize(memoryStream);
            }

            return(result);
        }
        /// <summary>
        /// Gets the stories.
        /// </summary>
        /// <param name="storyParametersRequest">The story parameters request.</param>
        /// <returns></returns>
        public async Task <APIResponse> GetStories(StoryParametersRequest storyParametersRequest)
        {
            try
            {
                string serializedStories;
                List <StoryResponse> stories;

                var encodedStories = await distributedCache.GetAsync(BlogServiceOperation.GetStoriesCacheName);

                if (encodedStories != null)
                {
                    serializedStories = Encoding.UTF8.GetString(encodedStories);
                    stories           = JsonConvert.DeserializeObject <List <StoryResponse> >(serializedStories);
                }
                else
                {
                    var client = httpClientFactory.CreateClient(BlogServiceOperation.serviceName);

                    UriBuilder url = new UriBuilder(servicesConfig.Blog + BlogServiceOperation.GetStories());
                    url.Query = QueryStringHelper.ConvertToQueryString(storyParametersRequest);

                    var response = await client.GetAsync(url.ToString());

                    stories = JsonConvert.DeserializeObject <List <StoryResponse> >(await response.Content.ReadAsStringAsync());

                    serializedStories = JsonConvert.SerializeObject(stories);
                    encodedStories    = Encoding.UTF8.GetBytes(serializedStories);
                    var options = new DistributedCacheEntryOptions()
                                  .SetSlidingExpiration(TimeSpan.FromMinutes(1))
                                  .SetAbsoluteExpiration(DateTime.Now.AddHours(1));

                    await distributedCache.SetAsync(BlogServiceOperation.GetStoriesCacheName, encodedStories, options);
                }

                return(new APIResponse(stories, HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "Exception in method 'GetStories()'");
                var exMessage = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                return(new APIResponse(exMessage, HttpStatusCode.InternalServerError));
            }
        }