Esempio n. 1
0
        /// <summary>
        /// 仿照memoryCache.GetOrCreateAsync的IDistributedCache版本
        /// </summary>
        public static async Task <TItem> GetOrCreateAsync <TItem>(
            this IDistributedCache cache,
            string key,
            Func <DistributedCacheEntryOptions, Task <TItem> > factory)
        {
            // 先从缓存中获取,有就直接返回
            var obj = cache.GetAsObject <TItem>(key);

            if (obj != null)
            {
                return(obj);
            }
            var entry = new DistributedCacheEntryOptions();

            // 没有的话,取了再添加到缓存里面
            var result = await factory(entry);

            cache.SetAsObject(key, result, entry);

            return(result);
        }
Esempio n. 2
0
        public User GetById(string id)
        {
            var cachedUser = _distributedCache.GetAsObject <User>(id);

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

            var guid = Guid.Parse(id);

            var dbUser = _unitOfWork.UserRepository.GetAsQueryable().FirstOrDefault(it => it.Id == guid);

            if (dbUser == null)
            {
                throw new NotFoundException("user.NotFound", "user doesn't not found!");
            }

            _distributedCache.SetAsObject(dbUser.Id.ToString(), dbUser);

            return(dbUser);
        }