/// <summary>
 /// 获取key缓存String类型数据
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 public T Get <T>(string key)
 {
     if (ContainsKey(key))
     {
         var result = JsonConvert.DeserializeObject <T>(_client.Get(key));
         return(result);
     }
     return(default(T));
 }
Exemple #2
0
        /// <summary>
                /// 取得缓存数据
                /// </summary>
                /// <typeparam name="T"></typeparam>
                /// <param name="key"></param>
                /// <returns></returns>
                public T GetCache <T>(string key) where T : class
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            T v = _cache.Get <T>(key);

            return(v);
        }
Exemple #3
0
        public async Task <TAgent> FetchById(string agentId)
        {
            var key = agentId;

            if (csredis.Exists(key))
            {
                return(JsonConvert.DeserializeObject <TAgent>(csredis.Get(key)));
            }
            else
            {
                return(null);
            }
        }
Exemple #4
0
        public T TryGetOrCreate <T>(string key, Func <T> func, int expireMS)
        {
            var val = _client.Get <T>(key);

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

            var rt = func();

            _client.Set(key, rt, RandomExpireMS(expireMS));
            return(rt);
        }
Exemple #5
0
        public async Task <ActionResult <String> > Connect(int id)
        {
            System.Diagnostics.Debug.WriteLine("connect to " + id);
            string name   = "mlab" + id;
            Stream stream = await client.Containers.GetContainerLogsAsync(name,
                                                                          new ContainerLogsParameters()
            {
                ShowStdout = true,
                ShowStderr = true
            });

            if (stream == null)
            {
                return(NotFound());
            }
            StreamReader reader = new StreamReader(stream, new UTF8Encoding(false));
            string       logs   = await reader.ReadToEndAsync();

            System.Diagnostics.Debug.WriteLine(logs);
            int start = logs.IndexOf("http://127.0.0.1");

            if (start < 0)
            {
                return(NotFound());
            }
            string left     = logs.Substring(start);
            int    end      = left.IndexOf("\n");
            string result   = left.Substring(0, end);
            string hostPort = cSRedisClient.Get(id.ToString());

            result = result.Replace("8888", hostPort);

            return(result);
        }
Exemple #6
0
        protected override void DoWork()
        {
            if (ModBusDataFactory.LineReady == 0)
            {
                //获取到工位派工单
                string orders = RedisClientRemote?.Get("LD:A01:MCIM:wc001");
                RedisClientLocal.Set("LD:A01:MCIM:wc001", orders);
                var orderc = RedisClientLocal.Get("LD:A01:MCIM:wc001");
                List <RMesDispatch> orderl = JsonExtension.JsonToModel <List <RMesDispatch> >(orderc);
                //暂存当前工单的产线标记
                ModBusDataFactory.OrderLine = orderl[0].LINE;
                foreach (RMesDispatch dispatch in orderl)
                {
                    ModBusDataFactory.dispatrchs.Enqueue(dispatch);
                }
                //从BC获取质量任务单,下发给检测机

                //从BC获取物料编号对应的料箱规格存放在本地
                //Repository _mesRepository = new Repository(SysConf.Main.DbMES);
                //var pROD_INFO = _mesRepository.Single<LD.MDCI.MESModels.TB_PROD_INFO>(w =>
                //    w.MATERIAL_CODE == orderl[0].MATERIAL_CODE);
                var rProdInfo = new RProdInfo();
                Dictionary <string, int> PackageInfo = InitizePackageInfo();
                int Package = PackageInfo[rProdInfo.PACKAGE];
                RedisClientLocal.Set($"LD:{ModBusDataFactory.OrderLine}:APCM:PACKAGE", Package);
                //拿到单子后不再取单子,机器变为忙碌状态;到加工完毕后改为空闲
                //ModbusConfModel confModel = ModbusConf.CnfModel.FirstOrDefault(v => v.Name == "PLC");
                RedisClientLocal.Set($"LD:{ModBusDataFactory.OrderLine}:APCM:READY", 1);
                ModBusDataFactory.LineReady = 1;
            }
        }
Exemple #7
0
        public Result DoHttpWork(Request req)
        {
            var key = req.Query["key"];

            if (key == null)
            {
                return(Result.Fail("参数错误"));
            }

            try
            {
                RedisClientLocal = new CSRedisClient(SysConf.Main.RedisLocal.ConnectStrings);
                Logger.Main.Info($"[{Program.ModuleName}]初始化LOCAL REDIS CLIENT成功: \"{SysConf.Main.RedisLocal.ConnectStrings}\"");
            }
            catch (Exception ex)
            {
                Logger.Main.Error($"[{Program.ModuleName}]初始化LOCAL REDIS CLIENT失败: \"{SysConf.Main.RedisLocal.ConnectStrings}\", {ex.Message}");
            }

            if (req.Method == "GET")
            {
                if (!RedisClientLocal.Exists(key))
                {
                    return(Result.Fail($"Key: {key} 不存在"));
                }

                return(Result.Success(RedisClientLocal.Get(key)));
            }
            else if (req.Method == "POST")
            {
                string content = req.Body.AsString();
                return(Result.Success(RedisClientLocal.Set(key, content)));
            }
            return(Result.Fail($"不支持{req.Method}方法"));
        }
 public T Get <T>(string key)
 {
     if (string.IsNullOrWhiteSpace(key))
     {
         throw new ArgumentNullException(nameof(key));
     }
     return(client.Get <T>(key));
 }
Exemple #9
0
 public static void M5_SetNxRemove(this CSRedisClient client, string key, string selfMark)
 {
     //判断是否是自己的锁
     if (client.Get(key) == selfMark)
     {
         client.Del(key);
     }
 }
Exemple #10
0
        /// <summary>
        /// 取出队列,全部处理,为空后退出
        /// </summary>
        /// <returns></returns>
        private async Task <bool> Read()
        {
            var id = client.RPopLPush(jobList, bakList);

            if (string.IsNullOrEmpty(id))
            {
                return(false);
            }

            var key   = $"msg:{Service.ServiceName}:{id}";
            var guard = $"guard:{Service.ServiceName}:{id}";

            if (!await client.SetNxAsync(guard, "Guard"))
            {
                await Task.Delay(RedisOption.Instance.MessageLockTime);

                return(true);
            }
            client.Expire(guard, RedisOption.Instance.MessageLockTime);

            var str = client.Get(key);

            if (string.IsNullOrEmpty(str))
            {
                logger.Warning(() => $"ReadList key empty.{key}");
                await client.DelAsync(key);

                await client.LRemAsync(bakList, 0, id);

                await client.DelAsync(guard);

                return(true);
            }
            IInlineMessage item;

            try
            {
                item = SmartSerializer.ToMessage(str);
            }
            catch (Exception ex)
            {
                logger.Warning(() => $"ReadList deserialize error.{ex.Message }.{key} =>{str}");
                await client.DelAsync(key);

                await client.LRemAsync(bakList, 0, id);

                await client.DelAsync(guard);

                return(true);
            }
            //item.Trace ??= TraceInfo.New(item.ID);
            item.Service = Service.ServiceName;

            _ = MessageProcessor.OnMessagePush(Service, item, true, null);

            return(true);
        }
Exemple #11
0
        /// <summary>
        /// get value by key
        /// </summary>
        /// <param name="KeyName"></param>
        /// <returns></returns>
        public T GetValue <T>(String KeyName)
        {
            if (conn == null)
            {
                throw new Exception("Connection has not initialize.");
            }

            return(conn.Get <T>(KeyName));
        }
Exemple #12
0
 public byte[] Get(string key)
 {
     if (this.caches.ContainsKey(key))
     {
         logger.LogInformation($"Found key: '{key}' at local");
         return(caches[key].GetData());
     }
     logger.LogInformation($"Fetch key: '{key}' from Redis");
     return(redisClient.Get <byte[]>(key));
 }
Exemple #13
0
        private string GetBypassCache()
        {
            string cache_status = null;

            if (rds_conn == null)
            {
                rds_conn = GetRedisClient();
            }
            cache_status = rds_conn.Get(GeetestConfig.GEETEST_BYPASS_STATUS_KEY);
            return(cache_status);
        }
Exemple #14
0
 /// <summary>
 /// 设置
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 internal static new T Get <T>(string key)
 {
     try
     {
         return(_redisManager.Get <T>(key));
     }
     catch (Exception)
     {
         return(default(T));
     }
 }
Exemple #15
0
        private static void Main(string[] args)
        {
            var csredis = new CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=1,poolsize=50,ssl=false,writeBuffer=10240");

            csredis.Set("name", "张三");//设置值。默认永不过期
            Console.WriteLine(csredis.Get("name"));

            csredis.Set("time", DateTime.Now, 1);
            Console.WriteLine(csredis.Get <DateTime>("time"));
            Thread.Sleep(1100);
            Console.WriteLine(csredis.Get <DateTime>("time"));

            // 列表
            csredis.RPush("list", "第一个元素");
            csredis.RPush("list", "第二个元素");
            csredis.LInsertBefore("list", "第二个元素", "我是新插入的第二个元素!");
            Console.WriteLine($"list的长度为{csredis.LLen("list")}");

            Console.WriteLine($"list的第二个元素为{csredis.LIndex("list", 1)}");
            // 哈希
            csredis.HSet("person", "name", "zhulei");
            csredis.HSet("person", "sex", "男");
            csredis.HSet("person", "age", "28");
            csredis.HSet("person", "adress", "hefei");
            Console.WriteLine($"person这个哈希中的age为{csredis.HGet<int>("person", "age")}");

            // 集合
            csredis.SAdd("students", "zhangsan", "lisi");
            csredis.SAdd("students", "wangwu");
            csredis.SAdd("students", "zhaoliu");
            Console.WriteLine($"students这个集合的大小为{csredis.SCard("students")}");
            Console.WriteLine($"students这个集合是否包含wagnwu:{csredis.SIsMember("students", "wangwu")}");

            //有序集合
            csredis.ZAdd("socre", (1, "张三"), (2, "李四"));
            csredis.ZCard("score");
            csredis.ZCount("score", 1, 3);

            Console.ReadLine();
        }
        public long?GetThrottleCount(IThrottleKey key, Limiter limiter)
        {
            string id    = CreateThrottleKey(key, limiter);
            var    value = CSRedis.Get(id);
            long   convert;

            if (long.TryParse(value, out convert))
            {
                return(convert);
            }

            return(null);
        }
Exemple #17
0
        public ReadOnlyMemory <byte>?Get(string key, CancellationToken cancellationToken)
        {
            var result = _client.Get <byte[]>(GetKey(key));

            // ReSharper disable once ConvertIfStatementToReturnStatement
            // ReSharper disable once UseNullPropagation
            if (result == null)
            {
                return(null);
            }

            return(result);
        }
Exemple #18
0
        /// <summary>CsRedis</summary>
        public IActionResult GetCurrentTimeForCsRedisCache()
        {
            using (var csredis = new CSRedisClient("47.100.220.174:6379,password=redis@pwd"))
            {
                var list = csredis.Get <List <string> >("x");
            }

            var watch = new Stopwatch();

            watch.Start();

            watch.Stop();

            return(Content($"{watch.ToString()},耗时:{watch.ElapsedMilliseconds}毫秒"));
        }
Exemple #19
0
        public async Task <IActionResult> UseCsRedisCore()
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            await Task.CompletedTask;
            var strRedisEndPoints = _configuration["DIMSUM_REDISENDPOINT"];
            var redisEndPoints    = strRedisEndPoints.Split('|').ToArray();

            _logger.LogInformation($"尝试连接Redis:{JsonConvert.SerializeObject(redisEndPoints)}");
            var csRedis = new CSRedisClient($"{_configuration["DIMSUM_MASTERSERVICENAME"]},password={_configuration["DIMSUM_REDISPWD"]}", redisEndPoints);

            RedisHelper.Initialization(csRedis);

            var value = csRedis.Get("username");

            stopWatch.Stop();
            return(Json(new { key = "username", value = value, spendTime = stopWatch.ElapsedMilliseconds }));
        }
Exemple #20
0
 public T Get <T>(string key)
 {
     return(_redisClient.Get <T>(key));
 }
Exemple #21
0
 public T Get <T>(string key)
 {
     return(_csredis.Get <T>(key));
 }
 public T Get <T>(string key) => _instance.Get <T>(key);
Exemple #23
0
 /// <summary>
 /// 获取单个key的值
 /// </summary>
 /// <param name="key">Redis Key</param>
 /// <returns></returns>
 public string StringGet(string key)
 {
     return(csredis.Get(key));
 }
 public void  普通()
 {
     rds.Set("test1", "123123", 60);
     rds.Get("test1");
     //函数名与 redis-cli 的命令相同,rds 一定是单例单例单例
 }
Exemple #25
0
 public static string GetString(string key)
 {
     return(mRedisInstance.Get(key));
 }
 public string GetKeyString(string key)
 {
     return(csClient.Get(key));
 }
        public RateLimitCounter Get(string id)
        {
            var key = GetKeyPrefix(id);

            return(_client.Get <RateLimitCounter>(key));
        }
 public string Get(string key)
 {
     return(_client.Get(key));
 }
Exemple #29
0
 /// <summary>
 /// 查询
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public string GetValue(string key)
 {
     return(redisConnection.Get(key));
 }