示例#1
0
        public override async Task <HashSet <string> > GetSetAsync(
            string key,
            Func <IEnumerable <string> > factory = null
            )
        {
            var result = IMemoryCacheService.Get <HashSet <string> >(key);

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

            var values = await IRedisGatewayService.GetSetAsync <string>(key);

            if (!values.HasContent())
            {
                values = factory.Invoke().ToHashSet();
            }

            await IRedisGatewayService.SetSetAsync(key, values);

            result = values.ToHashSet();

            if (_UseCacheAside)
            {
                var entryOptions = new CacheOptions <HashSet <string> >(expirationType: CacheExpirationType.NotRemoveable);
                IMemoryCacheService.Set(key, result, entryOptions);
            }

            return(result);
        }
        public void Get_WhenCalledWithKey_ReturnsConfigItem()
        {
            // Arrange
            var configItems = new List <IConfigItem>()
            {
                new ConfigItem("key1", "value1"),
                new ConfigItem("key2", "value2"),
                new ConfigItem("key3", "value3"),
            };

            var item = new ConfigItem("key1", "value1");

            _memoryCacheService.Contains(item.key).Returns(true);
            _memoryCacheService.Get(item.key).Returns(item);
            _fileManager.ReadAllEntriesFromFile().Returns(configItems);
            _configurationService = new ConfigurationService(_fileManager, _memoryCacheService);

            // Act
            var result = _configurationService.Get(item.key);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(item.key, result.key);
            Assert.AreEqual(item.value, result.value);
        }
        /// <summary>
        /// Get single entry from the configuration.
        /// </summary>
        /// <returns>Value associated with the key.</returns>
        public IConfigItem Get(string key)
        {
            if (!_memoryCacheService.Contains(key))
            {
                throw new KeyNotFoundException(string.Format("Configuration key not found {0}", key));
            }

            return(_memoryCacheService.Get(key));
        }
示例#4
0
        private List <Friend> GetCollectionInCache()
        {
            if (InMemoryCacheService.Exists(CacheKey) == false)
            {
                InMemoryCacheService.Insert(CacheKey, new List <Friend>());
            }

            return((List <Friend>)InMemoryCacheService.Get(CacheKey));
        }
示例#5
0
        public async Task <IDynamicCollection <T> > GetOrCreateAsync <T>(
            string listName,
            Func <IQueryable <T>, IQueryable <T> > query    = null,
            Func <IEnumerable <T>, IEnumerable <T> > sorter = null
            )
            where T : IEntity
        {
            var collectionKey = GetCollectionCacheKey(listName);

            var result =
                IMemoryCacheService.Get <IDynamicCollection <T> >(collectionKey);

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

            var IRepository = IContainerService.Get <IRepository <T> >();

            var idsKey    = GetIdsCacheKey(listName);
            var entityIds = await ICacheService.GetAsync <List <string> >(idsKey);

            if (entityIds == null)
            {
                var queryable = IRepository.GetQueryable();

                if (query != null)
                {
                    queryable = query(queryable);
                }

                var entities = await IDatabaseService.QueryAsync(queryable);

                await IEntityCacheService.Push(entities);

                entityIds =
                    entities
                    .Select(x => x?.Id)
                    .ToList();
            }
            else
            {
                await IRepository.GetManyByIdAsync(entityIds);
            }

            result =
                IDynamicCollectionFactory
                .Create(entityIds, sorter);

            IMemoryCacheService.Set(collectionKey, result);

            return(result);
        }
        /// <summary>
        /// Get entities from cache, if cache is empty get from database.
        /// </summary>
        /// <returns>The requested entities.</returns>
        public IEnumerable <T> GetAll()
        {
            var entities = _cacheService.Get(_key);

            if (entities == null)
            {
                CacheItemPolicy policy;
                entities = LoadEntities(out policy);
                _cacheService.Set(_key, entities, policy);
            }

            return(entities);
        }
示例#7
0
        public async Task <ActionResult <ExcutedResult> > SignIn(LoginUser userinfo)
        {
            try
            {
                QuartzService.StartJob <QuartzJob>("jobWork1", 1);
                //请求状态
                int statecode = (int)ExcutedResult.status.成功;


                var pwd = MD5Helper.MD5Encrypt32(userinfo.PassWord);

                //验证密码是否正确
                var user = await _userService.SignIn(userinfo.UserName, pwd);

                //不正确
                if (user == null)
                {
                    statecode = (int)ExcutedResult.status.账号密码错误;
                    return(ExcutedResult.SuccessResult("账号密码错误", statecode));
                }

                //从redis里面读取token  如果有值就继续用以前的Token 如果没有就重新生成
                var Token = _memoryCacheService.Get <Blog_Users>(user.UserToken);

                if (Token == null)
                {
                    //登录成功 生成Token
                    JwtTokenUtil jwtTokenUtil = new JwtTokenUtil(_configuration);

                    //生成Token
                    string token = jwtTokenUtil.GetToken(user);
                    user.UserToken = token;

                    //修改用户token
                    var updatetoken = await _userService.UpdateUserToken(user);

                    //修改成功后 并存在redis把用户存在redis缓存当中
                    if (updatetoken > 0)
                    {
                        _memoryCacheService.AddObject(token, user, new TimeSpan(1, 0, 0), false);
                    }
                }

                return(ExcutedResult.SuccessResult(user, statecode));
            }
            catch (Exception ex)
            {
                return(ExcutedResult.FailedResult(ex.Message, (int)ExcutedResult.status.请求失败));
            }
        }
示例#8
0
        public override async Task <T> GetAsync <T>(
            string key,
            Func <T> factory         = null,
            CacheOptions <T> options = null
            )
        {
            var cacheObj =
                _UseCacheAside
                                        ? IMemoryCacheService.Get <T>(key)
                                        : default(T);

            if (cacheObj is NotFound)
            {
                return(default(T));
            }

            var result = cacheObj == null ? default(T) : cacheObj;

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

            result = await IRedisGatewayService.GetAsync <T>(key);

            if (result == null)
            {
                if (factory != null)
                {
                    result = factory();
                }
            }

            if (result == null)
            {
                IMemoryCacheService.Set(key, NotFound.Shared);
                return(default(T));
            }

            if (_UseCacheAside)
            {
                IMemoryCacheService.Set(key, result, options);
            }

            await IRedisGatewayService.SetAsync(key, result);

            return(result);
        }
 private CacheReturnModel RetrieveCacheEntry(InvocationContext invocationContext, string key)
 {
     var cacheReturnObj = new CacheReturnModel();
     try
     {
         var returnType = invocationContext.GetMethodReturnType();
         cacheReturnObj.CacheEntry = IsReturnTypeGenericCollection(returnType) ?
             RetrieveCollectionFromCache(key, returnType) :
             _memoryCacheService.Get(key);
     }
     catch (Exception ex)
     {
         cacheReturnObj.CacheContext = CreateCacheExceptionInfoMessage(key, ex);
     }
     return cacheReturnObj;
 }
示例#10
0
        private string AppendFileChecksum(string filePath)
        {
            var fullFilePath = _httpCtx.Server.MapPath(filePath);

            if (_memoryCacheService.Get <FileSystemWatcherBase>(fullFilePath + "-fsw") == null)
            {
                // Ensure a file system watcher exists
                var fsw = _fswSvc.CreateFileSystemWatcher(fullFilePath);
                fsw.NotifyFilter = NotifyFilters.LastWrite;
                fsw.Changed     += new FileSystemEventHandler(OnFileCreatedOrChanged);
                _memoryCacheService.Default[fullFilePath + "-fsw"] = fsw;
            }

            // Get or update
            return((string)(_memoryCacheService.Default[fullFilePath]
                            ?? (_memoryCacheService.Default[fullFilePath] = CalculateFileHash(fullFilePath))));
        }
示例#11
0
        private async Task <(bool flag, List <RepositoryListItemEntity> repositories)> GetGitHubUserRepositoriesFromCache(IOperation operation)
        {
            return(await memoryCacheService.Get(MemoryCacheKey.GitHubUserRepositories, async() =>
            {
                IGitHubClientService gitHubClient;
                try
                {
                    gitHubClient = await portalSettingsService.GetGitHubClient(operation);
                }
                catch (NotFoundException)
                {
                    return (false, new List <RepositoryListItemEntity>());
                }

                var response = await new Repositories.GetUserRepositoriesRequest().SendRequest(operation, gitHubClient);
                return response.IsWithoutErrors() ? (true, response.Response) : throw CommonExceptions.UserRepositoriesCouldNotBeLoaded(operation, response.Output);
            }));
        public static T GetCacheObject(IMemoryCacheService cacheObj,
                                       CacheConfig config, string cacheKey)
        {
            T objectFromCache = default(T);

            if (!config.Enabled)
            {
                return(objectFromCache);
            }
            try
            {
                var response = (Cacheable <T>)cacheObj.Get(cacheKey);
                objectFromCache = response != null ? response.Model : default(T);
            }
            catch (Exception ex)
            {
                // LOG
            }
            return(objectFromCache);
        }
示例#13
0
 private async Task <Version.GetVersionResponse> GetCamundaVersionFromCache(IOperation operation)
 {
     return(await memoryCacheService.Get(MemoryCacheKey.CamundaVersion, async() => await new Version.GetVersionRequest().SendRequest(operation, camundaService, true)));
 }