Example #1
0
        public void QueryCurrency(IServiceProvider services)
        {
            var list = CurrencySet.GetAllCurrency();

            //失败隔30秒再请求一次
            if (list.Count == 0)
            {
                //Console.WriteLine("查询异常");
                logger.LogError("Query currency exception.");
            }
            else
            {
                //添加所有Currency到Redis数据库
                foreach (var item in list)
                {
                    try
                    {
                        RedisInstance.GetInstance().Set(item.Id, JsonHelper.ToJson(item), TimeSpan.FromSeconds(60));
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"Add coin {item.Name} to redis failed.");
                        logger.LogError($"Exception message: {ex.Message}");
                    }
                }
            }
        }
Example #2
0
        public ActionResult DownloadConfiguration(string host, int port)
        {
            var instance  = RedisInstance.GetInstance(host, port);
            var configZip = instance.GetConfigZip();

            return(new FileContentResult(configZip, "application/zip"));
        }
Example #3
0
        private void Instance_RedisInstanceConnected(object sender, TEventArgs <Redis.Management.RedisInstance> e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(() => { Instance_RedisInstanceConnected(sender, e); }));
            }
            else
            {
                _instance = e.Item;
                string txtName = string.Format("{0}:{1}", e.Item.IPEndPoint.Address, e.Item.IPEndPoint.Port);

                TreeNode node = treeView1.Nodes.Add(txtName, txtName, "redis");

                TreeNode dbfolderNode = node.Nodes.Add("Databases", "Databases", "folder", "folder");
                node.Tag = e.Item;
                foreach (RedisInstanceDatabase db in e.Item.Databases)
                {
                    string   key    = string.Format("db{0}", db.Index);
                    string   Text   = string.Format("db{0}[{1}]", db.Index, db.Keys);
                    TreeNode dbNode = dbfolderNode.Nodes.Add(key, Text, db.Keys > 0 ? "database" : "database-off", "database-selected");
                    dbNode.Tag = db;
                }
                dbfolderNode.Expand();


                TreeNode subscriptionNode = node.Nodes.Add("Subscription", "Subscription", "folder", "folder");


                node.Expand();
            }
        }
Example #4
0
        private RedisInstance Connecting(IPEndPoint endpoint, string password)
        {
            RedisInstance instance = new RedisInstance();

            try
            {
                bool isConnected = instance.Connect(endpoint, password);
                if (!isConnected)
                {
                    MessageBox.Show("无法连接到服务器,请确认服务器正常运行。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }catch (Exception ex)
            {
                Action action = new Action(() => {
                    if (this.InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(() => {
                            MessageBox.Show(string.Format("连接服务器过程错误。错误信息:{0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }));
                    }
                });

                action();
            }

            return(instance.Status == RedisInstanceStatus.Connected? instance:null);
        }
        public ActionResult PromoteToMaster(string node)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            var oldMaster = i.Master;

            try
            {
                var message = i.PromoteToMaster();
                i.Poll(true);
                if (oldMaster != null)
                {
                    oldMaster.Poll(true);
                }
                return(Json(new { message }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #6
0
        public ActionResult InstanceSummary(string node, string type)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(ContentNotFound("Could not find instance " + node));
            }

            switch (type)
            {
            case "config":
                return(View("Instance.Config", i));

            case "clients":
                return(View("Instance.Clients", i));

            case "info":
                return(View("Instance.Info", i));

            case "slow-log":
                return(View("Instance.SlowLog", i));

            default:
                return(ContentNotFound("Unknown summary view requested"));
            }
        }
Example #7
0
        public ActionResult QueryCurrencyInfo([FromQuery] string[] currencyIds)
        {
            if (currencyIds.Length == 0)
            {
                return(Json(new JsonResultModel(ReturnCode.ParameterError, "Parameter is not correct.")));
            }
            List <CurrencyInfo> currencyInfoList = new List <CurrencyInfo>();

            foreach (var currencyId in currencyIds)
            {
                try
                {
                    var currencyInfo = RedisInstance.GetInstance().Get <CurrencyInfo>(currencyId);
                    //若查询为空,等待0.5s重新查找
                    if (currencyInfo == null)
                    {
                        Thread.Sleep(500);
                        currencyInfo = RedisInstance.GetInstance().Get <CurrencyInfo>(currencyId);
                    }
                    currencyInfoList.Add(currencyInfo);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine("Query currency from redis got issue: ", ex.Message);
                    logger.LogError("Query currency from redis got issue: " + ex.Message);
                }
            }

            return(Json(new JsonResultModel(ReturnCode.Success, "Query successful.", currencyInfoList)));
        }
        public async Task <ActionResult> PromoteToMaster(string node)
        {
            var i = RedisInstance.Get(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            var oldMaster = i.Master;

            try
            {
                var message = i.PromoteToMaster();
                // We want these to be synchronous
                await i.PollAsync(true).ConfigureAwait(false);

                await oldMaster?.PollAsync(true);

                return(Json(new { message }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #9
0
        private IEnumerable <Instantiation> GenerateRedisAutoscalingRules(RuleGeneratorArguments arguments)
        {
            if (!arguments.DynamicStampProperties.RedisAutoscalingEnabled)
            {
                yield break;
            }

            var autoscalingAgentConfiguration = new RedisAutoscalingAgent.Configuration();

            if (arguments.DynamicStampProperties.RedisAutoscalingMaximumClusterMemoryAllowedMb > 0)
            {
                autoscalingAgentConfiguration.MaximumClusterMemoryAllowedMb = arguments.DynamicStampProperties.RedisAutoscalingMaximumClusterMemoryAllowedMb;
            }

            var redisAutoscalingAgent = new RedisAutoscalingAgent(autoscalingAgentConfiguration, arguments.EnvironmentResources.MonitorManagementClient);
            var configuration         = new RedisAutoscalingRule.Configuration(arguments.BaseConfiguration);

            var primaryRedisInstance = RedisInstance
                                       .FromPreloaded(arguments.EnvironmentResources.Azure, arguments.EnvironmentResources.RedisCaches[arguments.StampId.PrimaryRedisName])
                                       .ThrowIfFailure();

            var secondaryRedisInstance = RedisInstance
                                         .FromPreloaded(arguments.EnvironmentResources.Azure, arguments.EnvironmentResources.RedisCaches[arguments.StampId.SecondaryRedisName])
                                         .ThrowIfFailure();

            yield return(new Instantiation
            {
                Rule = new RedisAutoscalingRule(configuration, redisAutoscalingAgent, primaryRedisInstance, secondaryRedisInstance),
                PollingPeriod = TimeSpan.FromMinutes(10),
            });
        }
Example #10
0
 public frmDatabases(RedisInstance instance) : this()
 {
     _instance = instance;
     if (_instance != null)
     {
         this.TabText = string.Format("Databases [{0}]", _instance.IPEndPoint);
     }
 }
 public frmRedisMonitors(RedisInstance instance) : this()
 {
     _instance = instance;
     if (_instance != null)
     {
         this.DockHandler.TabText           = string.Format("服务器监控:{0}", _instance.IPEndPoint);
         _instance.Monitor.MonitorReceived += Monitor_MonitorReceived;
     }
 }
Example #12
0
        public ActionResult InstanceActions(string node)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            return(View("Instance.Actions", i));
        }
Example #13
0
        public ActionResult ClearAnalysis(string node, int db)
        {
            var instance = RedisInstance.GetInstance(node);

            if (instance == null)
            {
                return(TextPlain("Instance not found"));
            }
            instance.ClearDatabaseMemoryAnalysisCache(db);

            return(RedirectToAction("Analysis", new { node, db }));
        }
Example #14
0
        public ActionResult Analysis(string node, int db, bool runOnMaster = false)
        {
            var instance = RedisInstance.GetInstance(node);

            if (instance == null)
            {
                return(TextPlain("Instance not found"));
            }
            var analysis = instance.GetDatabaseMemoryAnalysis(db, runOnMaster);

            return(View("Server.Analysis.Memory", analysis));
        }
Example #15
0
        public ActionResult Instance(string node)
        {
            var instance = RedisInstance.GetInstance(node);

            var vd = new DashboardModel
            {
                Instances          = RedisInstance.AllInstances,
                CurrentInstance    = instance,
                View               = RedisViews.Instance,
                CurrentRedisServer = node,
                Refresh            = true
            };

            return(View(vd));
        }
Example #16
0
        public ActionResult Instance(string node, bool ajax = false)
        {
            var instance = RedisInstance.GetInstance(node);

            var vd = new DashboardModel
            {
                Instances          = RedisInstance.AllInstances,
                CurrentInstance    = instance,
                View               = DashboardModel.Views.Instance,
                CurrentRedisServer = node,
                Refresh            = true
            };

            return(View(ajax ? "Instance" : "Dashboard", vd));
        }
        public ActionResult InstanceActions(string node)
        {
            var h = RedisHost.Get(node);

            if (h != null)
            {
                return(PartialView("Server.Actions", h));
            }
            var i = RedisInstance.Get(node);

            if (i != null)
            {
                return(PartialView("Instance.Actions", i));
            }
            return(JsonNotFound());
        }
Example #18
0
        public static string SaveUserToken(string userId, TimeSpan timeSpan)
        {
            try
            {
                string token = GenerateUserToken();
                RedisInstance.GetInstance().Set(userId, token, timeSpan);

                return(token);
            }
            catch (Exception ex)
            {
                logger.LogError($"Save user {userId} token to redis failed.");
                logger.LogError($"Exception message: {ex.Message}");

                return(string.Empty);
            }
        }
Example #19
0
        private IEnumerable <Instantiation> GenerateRedisAutoscalingRules(SingleStampRuleArguments arguments)
        {
            if (!arguments.DynamicStampProperties.RedisAutoscalingEnabled)
            {
                yield break;
            }

            if (!arguments.EnvironmentResources.RedisCaches.ContainsKey(arguments.StampId.PrimaryRedisName) || !arguments.EnvironmentResources.RedisCaches.ContainsKey(arguments.StampId.SecondaryRedisName))
            {
                _logger.Error($"Attempt to create Redis autoscaler for stamp `{arguments.StampId}` failed due to missing Redis instance. Skipping rule");
                yield break;
            }

            var autoscalingAgentConfiguration = new RedisAutoscalingAgent.Configuration();

            if (arguments.DynamicStampProperties.RedisAutoscalingMaximumClusterMemoryAllowedMb > 0)
            {
                autoscalingAgentConfiguration.MaximumClusterMemoryAllowedMb = arguments.DynamicStampProperties.RedisAutoscalingMaximumClusterMemoryAllowedMb;
            }

            var azureMetricsClient    = new AzureMetricsClient(arguments.EnvironmentResources.MonitorManagementClient);
            var redisAutoscalingAgent = new RedisAutoscalingAgent(autoscalingAgentConfiguration, azureMetricsClient);
            var configuration         = new RedisAutoscalingRule.Configuration(arguments.BaseConfiguration);

            var primaryRedisInstance = RedisInstance
                                       .FromPreloaded(
                arguments.EnvironmentResources.Azure,
                arguments.EnvironmentResources.RedisCaches[arguments.StampId.PrimaryRedisName],
                readOnly: _configuration.ReadOnly)
                                       .ThrowIfFailure();

            var secondaryRedisInstance = RedisInstance
                                         .FromPreloaded(
                arguments.EnvironmentResources.Azure,
                arguments.EnvironmentResources.RedisCaches[arguments.StampId.SecondaryRedisName],
                readOnly: _configuration.ReadOnly)
                                         .ThrowIfFailure();

            yield return(new Instantiation
            {
                Rule = new RedisAutoscalingRule(configuration, redisAutoscalingAgent, primaryRedisInstance, secondaryRedisInstance),
                PollingPeriod = TimeSpan.FromMinutes(10),
            });
        }
Example #20
0
        public ActionResult KillClient(string node, string address)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            try
            {
                bool success = i.KillClient(address);
                return(Json(new { success }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #21
0
        public static bool DeleteUserToken(string userId)
        {
            try
            {
                if (String.IsNullOrEmpty(userId))
                {
                    return(false);
                }

                return(RedisInstance.GetInstance().Remove(userId));
            }
            catch (Exception ex)
            {
                logger.LogError($"Remove user {userId} token to redis failed.");
                logger.LogError($"Exception message: {ex.Message}");

                return(false);
            }
        }
Example #22
0
        public ActionResult Dashboard(string node)
        {
            var instances = RedisInstance.GetAll(node);

            if (instances.Count == 1 && instances[0] != null)
            {
                // In the 1 case, redirect
                return(RedirectToAction(nameof(Instance), new { node }));
            }
            var vd = new DashboardModel
            {
                Instances          = instances.Count > 1 ? instances : RedisModule.Instances,
                View               = node.HasValue() ? RedisViews.Server : RedisViews.All,
                CurrentRedisServer = node,
                Refresh            = true
            };

            return(View("Dashboard.Instances", vd));
        }
Example #23
0
        public ActionResult Dashboard(string node)
        {
            var instance = RedisInstance.GetInstance(node);

            if (instance != null)
            {
                return(RedirectToAction("Instance", new { node }));
            }

            var vd = new DashboardModel
            {
                Instances          = RedisInstance.AllInstances,
                View               = node.HasValue() ? RedisViews.Server : RedisViews.All,
                CurrentRedisServer = node,
                Refresh            = true
            };

            return(View("AllServers", vd));
        }
Example #24
0
        public ActionResult SlaveServer(string node, string newMaster)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            try
            {
                var success = i.SlaveTo(newMaster);
                i.Poll(true);
                return(Json(new { success }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #25
0
        public static string GetUserToken(string userId)
        {
            try
            {
                if (String.IsNullOrEmpty(userId))
                {
                    return(string.Empty);
                }

                string value = RedisInstance.GetInstance().Get(userId);
                return(value);
            }
            catch (Exception ex)
            {
                logger.LogError($"Save user {userId} token to redis failed.");
                logger.LogError($"Exception message: {ex.Message}");

                return(string.Empty);
            }
        }
Example #26
0
        public async Task <ActionResult> KeyPurge(string node, int db, string key)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            try
            {
                var removed = await i.KeyPurge(db, key);

                return(Json(new { removed }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
        private async Task <ActionResult> Deslave(string node, bool promote)
        {
            var i = RedisInstance.Get(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            var oldMaster = i.Master;

            try
            {
                var message = i.PromoteToMaster();
                if (promote)
                {
                    await i.SetSERedisTiebreakerAsync().ConfigureAwait(false);

                    await oldMaster?.ClearSERedisTiebreakerAsync();

                    await oldMaster?.SlaveToAsync(i.HostAndPort);
                }
                else
                {
                    await i.ClearSERedisTiebreakerAsync().ConfigureAwait(false);
                }
                // We want these to be synchronous
                await i.PollAsync(true).ConfigureAwait(false);

                await oldMaster?.PollAsync(true);

                return(Json(new { message }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #28
0
        private ActionResult PerformInstanceAction(string node, Func <RedisInstance, bool> action, bool poll = false)
        {
            var i = RedisInstance.GetInstance(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            try
            {
                var success = action(i);
                if (poll)
                {
                    i.Poll(true);
                }
                return(Json(new { success }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
        private async Task <ActionResult> PerformInstanceAction(string node, Func <RedisInstance, Task <bool> > action, bool poll = false)
        {
            var i = RedisInstance.Get(node);

            if (i == null)
            {
                return(JsonNotFound());
            }

            try
            {
                var success = await action(i).ConfigureAwait(false);

                if (poll)
                {
                    await i.PollAsync(true).ConfigureAwait(false);
                }
                return(Json(new { success }));
            }
            catch (Exception ex)
            {
                return(JsonError(ex.Message));
            }
        }
Example #30
0
        public static void Main(string[] args)
        {
            int    port     = 6379;
            string server   = "localhost";
            string password = null;

            if (args != null)
            {
                if (args.Length > 0)
                {
                    server = args[0];
                    if (args.Length > 1)
                    {
                        Int32.TryParse(args[1], out port);
                        if (args.Length > 2)
                        {
                            password = args[2];
                        }
                    }
                }
            }

            string configString = $"{server}:{port}";

            RedisInstance dbi = new RedisInstance(configString);

            Task.Run(async() =>
            {
                IDatabase db = await dbi.GetDatabaseAsync(0);

#if GENDATA
                for (int ndx = 0; ndx < 100000; ndx++)
                {
                    db.StringSet($"user:{ndx}", $"{ndx}");
                }
#endif // GENDATA

                SortedDictionary <string, RedisKeyInfo> items =
                    await dbi.ScanDatabaseAsync(0, "*",
                                                maxCount: 200000,
                                                includeLastAccessed: true,
                                                includeExpiry: true);
                foreach (string key in items.Keys)
                {
                    Console.WriteLine(items[key].ToString());
                    switch (items[key].Type)
                    {
                    default:
                        Console.WriteLine(
                            $"Unsupported type '{items[key].Type}'.");
                        break;

                    case RedisType.SortedSet:
                        foreach (SortedSetEntry entry
                                 in db.SortedSetScan(items[key]))
                        {
                            Console.WriteLine($"{entry.Score} : {entry.Element}");
                        }
                        break;

                    case RedisType.Hash:
                        foreach (HashEntry entry
                                 in db.HashScan(items[key]))
                        {
                            Console.WriteLine($"{entry.Name} : {entry.Value}");
                        }
                        break;

                    case RedisType.List:
                        Console.WriteLine(String.Join(", ",
                                                      await db.ListRangeAsync(items[key])));
                        break;

                    case RedisType.String:
                        Console.WriteLine(
                            await db.StringGetAsync(items[key]));
                        break;

                    case RedisType.Set:
                        Console.WriteLine(String.Join(", ",
                                                      db.SetScan(items[key])));
                        break;
                    }
                }
                Console.WriteLine($"Item count = {items.Count}");
            }).Wait();

            Console.ReadLine();
        }