예제 #1
0
        public void Push(MsgItem msg)
        {
            msg = MsgHelper.GetMsgItem(msg);
            Queue <MsgItem> msgs;

            try
            {
                msgs = cache.Get <Queue <MsgItem> >(MsgKey) ?? new Queue <MsgItem>();
            }
            catch (Exception ex)
            {
                msgs = new Queue <MsgItem>();
            }

            msgs.Enqueue(msg);
            if (msgs.Count > MaxLength)
            {
                //多余的 消息放到数据库缓存 准备存到数据库中
                IEnumerable <MsgItem> msgsToDBTemp = msgs.Take(msgs.Count - MaxLength).AsEnumerable <MsgItem>();
                Queue <MsgItem>       msgsToDB     = cache.Get <Queue <MsgItem> >(DBKey) ?? new Queue <MsgItem>();
                foreach (MsgItem item in msgsToDBTemp)
                {
                    msgsToDB.Enqueue(msgs.Dequeue());
                }
                if (msgsToDB.Count >= MaxLength)
                {
                    //写入数据库操作
                    //并清0 缓存
                    msgsToDB.Clear();
                }
                cache.Add(DBKey, msgsToDB);
            }
            cache.Add(MsgKey, msgs);
        }
        public ActionResult <IEnumerable <string> > Get()
        {
            _provider.CustomPrefixKey = "www:";//改边默认key
            _provider.Set("demo", "yyy", TimeSpan.FromMinutes(1));
            var str2 = _provider.Get("demo", () => { return("缓存"); }, TimeSpan.FromMinutes(1));

            _provider.CustomPrefixKey = "EEE:";//继续改边默认key
            var str3 = _provider.Get("demo", () => { return("缓存"); }, TimeSpan.FromMinutes(1));

            return(new string[] { "value1", "value2" });
        }
예제 #3
0
 public Task <bool> CheckVerficationCodeAsync(string antiForgetCode, string code)
 {
     return(Task.Factory.StartNew(() =>
     {
         string key = string.Format(V_CODE_FORMAT, antiForgetCode);
         var result = _redisCache.Get(key);
         _redisCache.GetDatabase().KeyDelete(key);
         return code.Trim() == result;
     }));
 }
예제 #4
0
        // GET: Test
        public ActionResult Index()
        {
            _log.Error("ERROR:test by fierce");
            _log.Debug("Debug:test by fierce");
            _log.Information("Information:test by fierce");
            _log.Fatal("Fatal:test by fierce");
            //RedisCache cache = new RedisCache();
            //_cache.Add("test1",new string[] { "111","222"});
            ViewBag.Test1 = _cache.Get <string[]>("test1");

            return(View());
        }
예제 #5
0
        public Carrinho Obter(string usuario)
        {
            var value = _redis.Get($"{_key}:carrinho:{usuario}");

            if (string.IsNullOrWhiteSpace(value))
            {
                var carrinho = new Carrinho();
                Salvar(usuario, carrinho);
                return(carrinho);
            }
            return(JsonConvert.DeserializeObject <Carrinho>(value));
        }
예제 #6
0
        public async Task <IActionResult> ByCountry([FromBody] string id)
        {
            var cacheKey       = id.GetHashCode().ToString();
            var previousResult = _redisCache.Get <PagedResults <Airline> >(cacheKey);

            if (previousResult == null)
            {
                previousResult = await _ddbService.GetAirlines(id, 20);

                _redisCache.Put(cacheKey, previousResult, TimeSpan.FromHours(24));
            }
            return(Json(previousResult));
        }
예제 #7
0
        public async Task <List <Produto> > GetProdutos()
        {
            var key   = "produtos";
            var value = _cache.Get(key);

            if (!string.IsNullOrEmpty(value))
            {
                var produtos = await _storage.GetProdutos();

                _cache.Set(key, JsonConvert.SerializeObject(produtos));
            }

            return(JsonConvert.DeserializeObject <List <Produto> >(value));
        }
예제 #8
0
        public async Task <List <Produto> > ObterProdutos()
        {
            var key   = "produtos";
            var value = _cache.Get(key);

            if (string.IsNullOrWhiteSpace(value))
            {
                var produtos = await _storage.ObterProdutos();

                _cache.Set(key, JsonConvert.SerializeObject(produtos));
                return(produtos);
            }
            return(JsonConvert.DeserializeObject <List <Produto> >(value));
        }
예제 #9
0
        public SYSUser GetRidis(string loginName)
        {
            //RedisCache _redisCache = new RedisCache();

            SYSUser userItem = new SYSUser();

            if (_IredisCache.Exist(loginName))
            {
                userItem = _IredisCache.Get <SYSUser>(loginName);
            }
            else
            {
                Task <List <SYSUser> > paramQueryData = _IsysUser.QueryStrAsync(a => a.LoginName == loginName);
                userItem = paramQueryData.Result.FirstOrDefault();
                _IredisCache.Set(loginName, userItem);
            }
            return(userItem);
        }
        public async Task <IActionResult> ListRoulettes()
        {
            List <Roulette> ListRoulettes;
            var             ListRoulettesCache = _RedisCache.Get <List <Roulette> >("ListRoulettes");

            if (ListRoulettesCache == null)
            {
                ListRoulettes = await _Roulette.ListRoulette();

                _RedisCache.Set <List <Roulette> >("ListRoulettes", ListRoulettes, _ExpirationTime);
            }
            else
            {
                ListRoulettes = ListRoulettesCache;
            }

            return(StatusCode(200, ListRoulettes));
        }
예제 #11
0
        static void Main(string[] args)
        {
            try
            {
                IRedisCache cache = CacheFactory.Resolve <IRedisCache>();

                var a = cache.Get("P4");

                Console.WriteLine(a);

                var aa = cache.GetAllKeys();

                Console.ReadLine();
            }
            catch (Exception ex)
            {
                throw new Exception("redis错误", ex);
            }
        }
예제 #12
0
        /// <summary>
        /// 异步的方式获取缓存数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        protected virtual async Task <T> GetAsync <T>(string key)
        {
            if (_perRequestCacheManager.IsExist(key))
            {
                return(_perRequestCacheManager.Get <T>(key, () => default(T), 0));
            }
            var serializedItem = await _db.StringGetAsync(key);

            if (!serializedItem.HasValue)
            {
                return(default(T));
            }
            var item = JsonConvert.DeserializeObject <T>(serializedItem);

            if (item == null)
            {
                return(default(T));
            }
            _perRequestCacheManager.Set(key, item, 0);
            return(item);
        }
예제 #13
0
 /// <summary>
 /// Get
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 public T Get <T>(string key)
 {
     return(_cache.Get <T>(key));
 }
예제 #14
0
        public void Intercept(IInvocation invocation)
        {
            var    cacheKey = "";
            object response;
            var    returnType = invocation.Method.ReturnType;

            if (returnType.FullName == "System.Void")
            {
                return;
            }
            var method = invocation.MethodInvocationTarget ?? invocation.Method;

            if (method.GetCustomAttributes(true).Any(m => m.GetType() == typeof(CachingAttribute)))
            {
                //获取自定义缓存键
                cacheKey = CustomCacheKey(invocation);
                //根据key获取相应的缓存值
                var cacheValue = _cache.GetValue(cacheKey);
                if (cacheValue != null)
                {
                    var returnTypeArguments = returnType.GenericTypeArguments;
                    if (typeof(Task).IsAssignableFrom(returnType))
                    {
                        //返回Task<T>
                        if (returnTypeArguments.Length > 0)
                        {
                            var returnTypeArgument = returnTypeArguments.FirstOrDefault();
                            // 核心1,直接获取 dynamic 类型
                            dynamic temp = Newtonsoft.Json.JsonConvert.DeserializeObject(cacheValue, returnTypeArgument);
                            //dynamic temp = System.Convert.ChangeType(cacheValue, resultType);
                            // System.Convert.ChangeType(Task.FromResult(temp), type);
                            response = Task.FromResult(temp);
                        }
                        else
                        {
                            response = Task.Yield();
                        }
                    }
                    else
                    {
                        // 核心2,要进行 ChangeType
                        response = System.Convert.ChangeType(_cache.Get <object>(cacheKey), returnType);
                    }

                    //将当前获取到的缓存值,赋值给当前执行方法
                    invocation.ReturnValue = response;
                    return;
                }
            }
            //去执行当前的方法
            invocation.Proceed();
            //存入缓存
            if (!string.IsNullOrWhiteSpace(cacheKey))
            {
                if (typeof(Task).IsAssignableFrom(returnType))
                {
                    var resultProperty = returnType.GetProperty("Result");
                    response = resultProperty.GetValue(invocation.ReturnValue);
                }
                else
                {
                    response = invocation.ReturnValue;
                }
                if (response == null)
                {
                    response = string.Empty;
                }
                var abs = ((CachingAttribute)method.GetCustomAttributes(true)
                           .FirstOrDefault(m => m.GetType() == typeof(CachingAttribute)))?.AbsoluteExpiration ?? 10;
                _cache.Set(cacheKey, response, TimeSpan.FromMinutes(abs));
            }
        }
예제 #15
0
 public List <string> Top10ProductNames()
 {
     return(_cache.Get("Top10ProductList", 60, () => (from p in _db.Products select p.Name).Take(10).ToList()));
 }
예제 #16
0
        // ReSharper disable once MethodTooLong
        private async Task ParseAvlDataAsync(TcpClient client, NetworkStream stream, string imei)
        {
            try
            {
                Trace.TraceInformation("IMEI received : " + imei);

                _log.Information($"{DateTime.Now} -IMEI received: {imei}");

                Trace.TraceInformation("--------------------------------------------");
                Byte[] b = { 0x01 };
                await stream.WriteAsync(b, 0, 1).ConfigureAwait(false);

                var modem = _redisCache.Get <CreateBoxCommand>(imei);

                while (true)
                {
                    stream = client.GetStream();
                    byte[] buffer = new byte[client.ReceiveBufferSize];
                    await stream.ReadAsync(buffer, 0, client.ReceiveBufferSize).ConfigureAwait(false);

                    List <byte> list = new List <byte>();
                    foreach (var b1 in buffer.Skip(9).Take(1))
                    {
                        list.Add(b1);
                    }
                    int dataCount = Convert.ToInt32(list[0]);
                    var bytes     = Convert.ToByte(dataCount);
                    if (client.Connected)
                    {
                        await stream.WriteAsync(new byte[] { 0x00, 0x00, 0x00, bytes }, 0, 4).ConfigureAwait(false);
                    }

                    var gpsResult = ParseAvlData(imei, buffer);

                    if (!gpsResult.Any() && imei.Any())
                    {
                        continue;
                    }
                    var events = new TLGpsDataEvents
                    {
                        Id     = Guid.NewGuid(),
                        Events = gpsResult
                    };
                    await _bus.Publish(events).ConfigureAwait(false);

                    var lastGpsData = gpsResult.Last();
                    if (modem == null)
                    {
                        modem      = new CreateBoxCommand();
                        modem.Imei = imei;
                    }
                    modem.Longitude           = lastGpsData.Long;
                    modem.Latitude            = lastGpsData.Lat;
                    modem.LastValidGpsDataUtc = lastGpsData.DateTimeUtc;
                    modem.Speed = lastGpsData.Speed;
                    await _bus.Publish(modem).ConfigureAwait(false);

                    // break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                client.Close();
                throw;
            }
        }
예제 #17
0
        public void GetTest(string key)
        {
            var value = _cache.Get <string>(key);

            Assert.AreEqual(value, "张三");
        }