コード例 #1
0
        /// <summary>
        /// 根据ID获取ConnectionConfig
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public RedisConnConfig GetConnConfigById(int id)
        {
            RedisConnConfig config = null;

            _redisConnDict.TryGetValue(id, out config);
            return(config);
        }
コード例 #2
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="fileFullPath"></param>
        public void Init(string fileFullPath)
        {
            _configDoc     = XElement.Load(fileFullPath);
            _redisConnDict = new ConcurrentDictionary <int, RedisConnConfig>();
            RedisConnConfig config = null;

            _index = 0;

            IEnumerator <XElement> enumerator = _configDoc.Elements("RedisConnection").GetEnumerator();

            while (enumerator.MoveNext())
            {
                XElement element = enumerator.Current;
                Interlocked.Increment(ref _index);

                string host = element.Attribute("Host").Value;
                if (_redisConnDict.ContainsKey(_index))
                {
                    continue;
                }

                config      = new RedisConnConfig();
                config.Id   = _index;
                config.Host = GetAttributeValue(element, "Host");
                config.Name = GetAttributeValue(element, "Name");
                config.Port = GetAttributeValue(element, "Port").ToInt();
                config.Auth = GetAttributeValue(element, "Auth");
                config.ConnectionTimeOut       = GetAttributeValue(element, "ConnectionTimeOut").ToInt();
                config.CommandExecutionTimeOut = GetAttributeValue(element, "CommandExecutionTimeOut").ToInt();

                _redisConnDict.TryAdd(_index, config);
            }
        }
コード例 #3
0
        /// <summary>
        /// 绑定数据库
        /// </summary>
        /// <param name="parentNode"></param>
        /// <param name="dicDbInfo"></param>
        /// <param name="config"></param>
        private void BindDbToTree(TreeNode parentNode, Dictionary <long, long> dicDbInfo
                                  , RedisConnConfig config)
        {
            if (parentNode == null)
            {
                return;
            }

            parentNode.Nodes.Clear();
            // 添加节点
            foreach (var info in dicDbInfo)
            {
                var nodeInfo = new RedisDbNodeInfo();
                nodeInfo.ParentHost = config.Host;
                nodeInfo.ParentPort = config.Port;
                nodeInfo.Db         = info.Key;

                string nodeName = string.Format("db{0}({1})", info.Key, info.Value);

                var node = new TreeNode(nodeName);
                node.Tag        = nodeInfo;
                node.ImageIndex = Index_RedisDb;
                parentNode.Nodes.Add(node);
                parentNode.Expand();
            }
            treDBList.Refresh();
        }
コード例 #4
0
        public CacheDb(RedisConnConfig config)
        {
            string str = $"{config.conn}:{config.port},password={config.password},defaultDatabase={config.database},poolsize={config.poolsize},ssl={config.isSSL},writeBuffer={config.writeBuffer},prefix={config.prefix}";

            var csredis = new CSRedis.CSRedisClient(str);

            Initialization(csredis);
        }
コード例 #5
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="config"></param>
        public RedisClient(RedisConnConfig config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("The Argument config is null.");
            }

            this._config       = config;
            this._socketClient = new RedisSocketClient(this._config.Host, this._config.Port,
                                                       this._config.Auth, this._config.ConnectionTimeOut);

            if (this._socketClient == null)
            {
                throw new ArgumentException("The RedisSocketClient is null.");
            }
        }
コード例 #6
0
        private void AddRedisConnWin_Closing(object sender, CancelEventArgs e)
        {
            AddRedisConnWin win = sender as AddRedisConnWin;

            if (win.Tag != null && win.Tag.GetType().Name == "RedisConnConfig")
            {
                RedisConnConfig config = win.Tag as RedisConnConfig;
                if (win.ShowType == 0)
                {
                    Common.ConnConfigList.Add(config.ConnName, config);
                    nodes.Add(new Node {
                        Name = config.ConnName, NodeType = NodeType.Connnection
                    });
                }
                else
                {
                    Common.ConnConfigList[config.ConnName] = config;
                    (tvConn.SelectedItem as Node).Name     = config.ConnName;
                }
                RedisHelper.WriteConnList(Common.ConnConfigList);
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            RedisConnConfig config = new RedisConnConfig
            {
                conn     = "192.168.1.1",
                port     = 6379,
                password = "******",
                database = 13,
                poolsize = 50,
                prefix   = "key_"
            };
            string    guid    = Guid.NewGuid().ToString("N");
            CacheDb   cacheDb = new CacheDb(config);
            Stopwatch sw      = new Stopwatch();

            sw.Start();
            for (int i = 0; i < 10; i++)
            {
                CacheDb.Set("Method1_" + i, i);
                Console.WriteLine(CacheDb.RandomKey());;
            }
            sw.Stop();
            TimeSpan ts1 = sw.Elapsed;

            Console.WriteLine($"方法1总耗时{ts1.TotalMilliseconds}ms");

            Stopwatch sw2 = new Stopwatch();

            RedisHelper.Initialization(new CSRedis.CSRedisClient("192.168.1.1:6379,password=12345678,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key"));
            sw2.Start();

            for (int i = 0; i < 10; i++)
            {
                RedisHelper.Set("Method2_" + i, i);
                Console.WriteLine(RedisHelper.RandomKey());
            }
            sw2.Stop();
            TimeSpan ts2 = sw2.Elapsed;

            Console.WriteLine($"方法2总耗时{ts2.TotalMilliseconds}ms");


            //切换数据库
            var connectionString = "192.168.1.1:6379,password=12345678,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍";
            var redis            = new CSRedisClient[4]; //定义成单例

            for (int a = 0; a < 4; a++)
            {
                redis[a] = new CSRedisClient(connectionString + ",defaultDatabase=" + a);
            }

            for (int i = 0; i < 2; i++)
            {
                redis[(int)Enum.Ali].Set("12" + Guid.NewGuid().ToString(), "12");
                redis[(int)Enum.BaiDu].Set("13" + Guid.NewGuid().ToString(), "13");
                redis[(int)Enum.QQ].Set("14" + Guid.NewGuid().ToString(), "14");
                redis[(int)Enum.Wechat].Set("15" + Guid.NewGuid().ToString(), "15");
            }

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    Console.WriteLine($"Redis{j}里面的一个随机值:" + redis[j].RandomKey());
                }
            }



            Console.WriteLine("Hello World!");
        }
コード例 #8
0
        private void TreeViewItem_MouseDoubleClick(object sender, RoutedEventArgs e)
        {
            Node node = tvConn.SelectedItem as Node;

            if (node.NodeType == NodeType.Connnection)
            {
                if (!redisConns.ContainsKey(node.Name))
                {
                    try
                    {
                        RedisConnConfig       config = node.Value as RedisConnConfig;
                        ConnectionMultiplexer conn   =
                            ConnectionMultiplexer.Connect(config.GetConnectionStr());
                        redisConns.Add(node.Name, conn);
                        IServer server = conn.GetServer(config.GetHostAndPortStr());
                        KeyValuePair <string, string>[] kvs = server.ConfigGet("databases");
                        int databasesNum = int.Parse(kvs[0].Value);
                        for (int i = 0; i < databasesNum; i++)
                        {
                            node.Nodes.Add(new Node
                            {
                                Name     = "db" + i,
                                NodeType = NodeType.Database,
                                Value    = i,
                                Nodes    = new ObservableCollection <Node>()
                            });
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Connect failed!");
                    }
                }
            }
            else if (node.NodeType == NodeType.Database)
            {
                int  dbNum                   = (int)node.Value;
                Node nodeParent              = GetConnectionNode(node);
                ConnectionMultiplexer conn   = redisConns[nodeParent.Name];
                RedisConnConfig       config = nodeParent.Value as RedisConnConfig;
                IServer server               = conn.GetServer(config.GetHostAndPortStr());
                // show all keys
                IEnumerable <RedisKey> keysNew = server.Keys(dbNum, pattern: "*");
                if (node.Nodes.Count > 0)
                {
                    foreach (var keyNew in keysNew)
                    {
                        if (IsKeyNameExists(keyNew, node.Nodes))
                        {
                            continue;
                        }
                        else
                        {
                            node.Nodes.Add(new Node
                            {
                                Name     = keyNew.ToString(),
                                NodeType = NodeType.Key,
                                Value    = keyNew,
                                Nodes    = new ObservableCollection <Node>()
                            });
                        }
                    }
                }
                else
                {
                    foreach (var key in keysNew)
                    {
                        node.Nodes.Add(new Node
                        {
                            Name     = key.ToString(),
                            NodeType = NodeType.Key,
                            Value    = key,
                            Nodes    = new ObservableCollection <Node>()
                        });
                    }
                }
            }
            else if (node.NodeType == NodeType.Key)
            {
                RedisKey key   = (RedisKey)node.Value;
                Node[]   nodes = GetConnectionAndDBNode(node);
                if (nodes != null)
                {
                    Node nodeConn = nodes[0];
                    Node nodeDB   = nodes[1];
                    ConnectionMultiplexer conn = redisConns[nodeConn.Name];
                    IDatabase             db   = conn.GetDatabase((int)nodeDB.Value);
                    txtKeyType.Text = db.KeyType(key).ToString();
                    txtKeyName.Text = node.Name;
                    TimeSpan?span = db.KeyTimeToLive(key);
                    txtTTL.Text = "-1" ?? ((TimeSpan)span).Seconds.ToString();
                }
            }
            e.Handled = true;
        }