天天看點

c# 周遊memcached

public void testMe()
        {
            string[] ips = System.Configuration.ConfigurationManager.AppSettings["MemcachedServers"].Split(',');

            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(ips);
            pool.Initialize();

            MemcachedClient client = new MemcachedClient();
            client.PrimitiveAsString = true;//加這個參數,可以與其他程式混寫緩存
            client.EnableCompression = true;

            SockIO sock = pool.GetConnection("127.0.0.1:11211");
            sock.Write(UTF8Encoding.UTF8.GetBytes("stats items \r\n"));
            sock.Flush();

            List<int> listIds = new List<int>();

            while (true)
            {
                string line = sock.ReadLine();
                if (line.StartsWith("END"))
                {
                    break;
                }

                if (line.StartsWith("STAT"))
                {
                    string[] info = line.Split(' ');
                    string[] tmpid = info[1].Split(':');
                    int id = int.Parse(tmpid[1]);
                    if (!listIds.Contains(id))
                    {
                        listIds.Add(id);
                    }
                }
            }

            List<string> listKey = new List<string>();

            Hashtable hs = new Hashtable();

            foreach (int id in listIds)
            {
                sock.Write(UTF8Encoding.UTF8.GetBytes(string.Format("stats cachedump {0} 0 \r\n", id)));
                sock.Flush();
                while (true)
                {
                    string line = sock.ReadLine();
                    Debug.WriteLine(line);

                    if (line.StartsWith("END"))
                    {
                        break;
                    }

                    if (line.StartsWith("ITEM"))
                    {
                        string[] info = line.Split(' ');
                        listKey.Add(info[1]);

                        hs.Add(info[1], "");
                    }
                }
            }

            foreach (string key in listKey)
            {
                sock.Write(UTF8Encoding.UTF8.GetBytes(string.Format("get {0}  \r\n", key)));
                sock.Flush();
                string value = "";
                while (true)
                {
                    string line = sock.ReadLine();

                    if (line.StartsWith("END"))
                    {
                        break;
                    }
                    if (!line.StartsWith("VALUE"))
                    {
                        value = line;
                    }
                }
                hs[key] = value;
            }

            sock.Close();

            foreach (DictionaryEntry entry in hs)
            {
                Debug.WriteLine("{0}={1}", entry.Key, entry.Value);
            }

        }