示例#1
0
        private Dictionary <string, string> stats(HostNode pool)
        {
            if (pool == null)
            {
                return(null);
            }
            Dictionary <string, string> dic = new Dictionary <string, string>();

            hostServer.Execute(pool, delegate(MSocket socket)
            {
                using (RedisCommand cmd = new RedisCommand(socket, 1, "info"))
                {
                }
                string result = socket.ReadResponse();
                if (!string.IsNullOrEmpty(result) && (result[0] == '$' || result == "+OK"))
                {
                    string line = null;
                    while (true)
                    {
                        line = socket.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        string[] s = line.Split(':');
                        dic.Add(s[0], s[1]);
                    }
                }
            });
            return(dic);
        }
示例#2
0
文件: MSocket.cs 项目: ImQdf/cyqdata
        public MSocket(HostNode socketPool, IPEndPoint endPoint)
        {
            this.socketPool = socketPool;
            CreateTime      = DateTime.Now;

            //Set up the socket.
            socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, true);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, sendReceiveTimeout);
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, sendReceiveTimeout);
            socket.ReceiveTimeout = sendReceiveTimeout;
            socket.SendTimeout    = sendReceiveTimeout;

            //socket.SendBufferSize = 1024 * 1024;

            //Do not use Nagle's Algorithm
            //socket.NoDelay = true;

            //Establish connection asynchronously to enable connect timeout.
            IAsyncResult result  = socket.BeginConnect(endPoint, null, null);
            bool         success = result.AsyncWaitHandle.WaitOne(connectTimeout, false);

            if (!success)
            {
                try { socket.Close(); }
                catch { }
                throw new SocketException();
            }
            socket.EndConnect(result);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
示例#3
0
        internal void Execute(HostNode host, UseSocket use)
        {
            MSocket sock = null;

            try
            {
                //Acquire a socket
                sock = host.Acquire();

                //Use the socket as a parameter to the delegate and return its result.
                if (sock != null)
                {
                    use(sock);
                }
            }
            catch (Exception e)
            {
                logger.Error("Error in Execute: " + host.Host, e);

                //Socket is probably broken
                if (sock != null)
                {
                    sock.Close();
                }
            }
            finally
            {
                if (sock != null)
                {
                    sock.ReturnPool();
                }
            }
        }
示例#4
0
        private Dictionary <string, string> GetInfoByHost(HostNode host, bool isBackup)
        {
            Dictionary <string, string> result = new Dictionary <string, string>();

            if (!host.IsEndPointDead)
            {
                if (!isBackup)
                {
                    OkServer++;
                }
                result.Add("Status", "Ok");
                result.Add("Sockets in pool", host.Poolsize.ToString());
                result.Add("Acquired sockets", host.Acquired.ToString());
                result.Add("Sockets reused", host.ReusedSockets.ToString());
                result.Add("New sockets created", host.NewSockets.ToString());
                result.Add("New sockets failed", host.FailedNewSockets.ToString());
                result.Add("Sockets died in pool", host.DeadSocketsInPool.ToString());
                result.Add("Sockets died on return", host.DeadSocketsOnReturn.ToString());
            }
            else
            {
                if (!isBackup)
                {
                    ErrorServer++;
                }
                result.Add("Status", "Dead , next retry at : " + host.DeadEndPointRetryTime);
                result.Add("Error", host.Error);
                if (host.HostNodeBak != null)
                {
                    result.Add("Backup - " + host.HostNodeBak.Host, JsonHelper.ToJson(GetInfoByHost(host.HostNodeBak, true)));
                }
            }

            return(result);
        }
示例#5
0
 private void AddHost(MList <string> hosts)
 {
     foreach (string host in hosts.List)
     {
         HostNode instance = new HostNode(this, host);
         instance.OnAfterSocketCreateEvent += new HostNode.OnAfterSocketCreateDelegate(instance_OnAfterSocketCreateEvent);
         hostList.Add(host, instance);
     }
 }
示例#6
0
        public MSocket(HostNode socketPool, string host)
        {
            this.hostNode = socketPool;
            CreateTime    = DateTime.Now;
            socket        = SocketCreate.New(host);

            //Wraps two layers of streams around the socket for communication.
            stream = new BufferedStream(new NetworkStream(socket, false));
        }
示例#7
0
        //internal HostInstance GetSocketPool(string host)
        //{
        //    return Array.Find(HostList, delegate(HostInstance socketPool) { return socketPool.Host == host; });
        //}

        /// <summary>
        /// This method executes the given delegate on a socket from the server that corresponds to the given hash.
        /// If anything causes an error, the given defaultValue will be returned instead.
        /// This method takes care of disposing the socket properly once the delegate has executed.
        /// </summary>
        internal T Execute <T>(uint hash, T defaultValue, UseSocket <T> use)
        {
            HostNode node = GetHost(hash);

            if (node.HostNodeBak == null && hostServerBak != null)
            {
                //为主Socket池挂接备份的Socket池
                node.HostNodeBak = hostServerBak.GetHost(hash, node.Host);
            }
            return(Execute(node, defaultValue, use));
        }
示例#8
0
 public bool FlushAll()
 {
     foreach (KeyValuePair <string, HostNode> item in hostServer.HostList)
     {
         HostNode pool = item.Value;
         hostServer.Execute(pool, delegate(MSocket socket)
         {
             using (RedisCommand cmd = new RedisCommand(socket, 1, "flushall"))
             {
                 cmd.Send();
                 socket.SkipToEndOfLine();
             }
         });
     }
     return(true);
 }
示例#9
0
        private Dictionary <string, string> stats(HostNode pool)
        {
            if (pool == null)
            {
                return(null);
            }
            Dictionary <string, string> result = new Dictionary <string, string>();

            hostServer.Execute(pool, delegate(MSocket socket)
            {
                socket.Write("stats\r\n");
                string line;
                while (!(line = socket.ReadResponse().TrimEnd('\0', '\r', '\n')).StartsWith("END"))
                {
                    string[] s = line.Split(' ');
                    result.Add(s[1], s[2]);
                }
            });
            return(result);
        }
示例#10
0
        public bool FlushAll(TimeSpan delay, bool staggered)
        {
            bool noerrors = true;
            uint count    = 0;

            foreach (KeyValuePair <string, HostNode> item in hostServer.HostList)
            {
                HostNode pool = item.Value;
                hostServer.Execute(pool, delegate(MSocket socket)
                {
                    uint delaySeconds = (staggered ? (uint)delay.TotalSeconds * count : (uint)delay.TotalSeconds);
                    //Funnily enough, "flush_all 0" has no effect, you have to send "flush_all" to flush immediately.
                    socket.Write("flush_all " + (delaySeconds == 0 ? "" : delaySeconds.ToString()) + "\r\n");
                    if (!socket.ReadResponse().StartsWith("OK"))
                    {
                        noerrors = false;
                    }
                    count++;
                });
            }
            return(noerrors);
        }
示例#11
0
        private object[] get(string command, string[] keys, bool keysAreChecked, uint[] hashes, out ulong[] uniques)
        {
            //Check arguments.
            if (keys == null || hashes == null)
            {
                throw new ArgumentException("Keys and hashes arrays must not be null.");
            }
            if (keys.Length != hashes.Length)
            {
                throw new ArgumentException("Keys and hashes arrays must be of the same length.");
            }
            uniques = new ulong[keys.Length];

            //Avoid going through the server grouping if there's only one key.
            if (keys.Length == 1)
            {
                return(new object[] { get(command, keys[0], keysAreChecked, hashes[0], out uniques[0]) });
            }

            //Check keys.
            if (!keysAreChecked)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    checkKey(keys[i]);
                }
            }

            //Group the keys/hashes by server(pool)
            Dictionary <HostNode, Dictionary <string, List <int> > > dict = new Dictionary <HostNode, Dictionary <string, List <int> > >();

            for (int i = 0; i < keys.Length; i++)
            {
                Dictionary <string, List <int> > getsForServer;
                HostNode pool = hostServer.GetHost(hashes[i]);
                if (!dict.TryGetValue(pool, out getsForServer))
                {
                    dict[pool] = getsForServer = new Dictionary <string, List <int> >();
                }

                List <int> positions;
                if (!getsForServer.TryGetValue(keys[i], out positions))
                {
                    getsForServer[keys[i]] = positions = new List <int>();
                }
                positions.Add(i);
            }

            //Get the values
            object[] returnValues = new object[keys.Length];
            ulong[]  _uniques     = new ulong[keys.Length];
            foreach (KeyValuePair <HostNode, Dictionary <string, List <int> > > kv in dict)
            {
                hostServer.Execute(kv.Key, delegate(MSocket socket)
                {
                    //Build the get request
                    StringBuilder getRequest = new StringBuilder(command);
                    foreach (KeyValuePair <string, List <int> > key in kv.Value)
                    {
                        getRequest.Append(" ");
                        getRequest.Append(key.Key);
                    }
                    getRequest.Append("\r\n");

                    //Send get request
                    socket.Write(getRequest.ToString());

                    //Read values, one by one
                    object gottenObject;
                    string gottenKey;
                    ulong unique;
                    while (readValue(socket, out gottenObject, out gottenKey, out unique))
                    {
                        foreach (int position in kv.Value[gottenKey])
                        {
                            returnValues[position] = gottenObject;
                            _uniques[position]     = unique;
                        }
                    }
                });
            }
            uniques = _uniques;
            return(returnValues);
        }