Asp.net (C #) traverses the memcached cache object

Source: Internet
Author: User

STATS command

Traversing the memcached cache object (C #)
For performance considerations, memcached does not provide the traversal function, but we can use the following two stats commands to obtain all the cache objects.
1. stats items

Displays the number of items in each slab.
2. stats cachedump slab_id limit_num
Displays the list of the first limit_num keys in a slab. Format: ITEM key_name [value_length B; expire_time | access_time s]
In addition to the above two, memcached also provides the following commands:

3. stats
4. stats reset
5. stats malloc
6. stats maps
7. stats sizes
8. stats slabs
9. stats detail [on | off | dump]
The usage of life order is different. please google it on your own. For memcached data storage and memory allocation, you will have the opportunity to write it again.

Add Cache
Add several keys locally, as shown below:

Program Implementation
Because it must be called in c #, the client needs to execute the STATS command. You can directly refer to the implementation in DiscuzNT3.0.
DiscuzNT: http://download.comsenz.com/DiscuzNT/src/
After downloading the program, find these two classes in the Discuz. Cache project: MemCached. cs and MemCachedClient. cs.
The following methods are used:
MemCached. GetStats
Code
Copy codeThe Code is as follows:
/// <Summary>
/// Obtain the data cached by the server
/// </Summary>
/// <Param name = "serverArrayList"> list of services to be accessed </param>
/// <Returns> return information </returns>
Public static ArrayList GetStats (ArrayList serverArrayList, Stats statsCommand, string param)
{
ArrayList statsArray = new ArrayList ();
Param = Utils. StrIsNullOrEmpty (param )? "": Param. Trim (). ToLower ();
String commandstr = "stats ";
// Convert the stats Command Parameters
Switch (statsCommand)
{
Case Stats. Reset: {commandstr = "stats reset"; break ;}
Case Stats. Malloc: {commandstr = "stats malloc"; break ;}
Case Stats. Maps: {commandstr = "stats maps"; break ;}
Case Stats. Sizes: {commandstr = "stats sizes"; break ;}
Case Stats. Slabs: {commandstr = "stats slabs"; break ;}
Case Stats. Items: {commandstr = "stats"; break ;}
Case Stats. CachedDump:
{
String [] statsparams = Utils. SplitString (param ,"");
If (statsparams. Length = 2)
If (Utils. IsNumericArray (statsparams ))
Commandstr = "stats cachedump" + param;
Break;
}
Case Stats. Detail:
{
If (string. Equals (param, "on") | string. Equals (param, "off") | string. Equals (param, "dump "))
Commandstr = "stats detail" + param. Trim ();
Break;
}
Default: {commandstr = "stats"; break ;}
}
// Load the returned value
Hashtable stats = MemCachedManager. CacheClient. Stats (serverArrayList, commandstr );
Foreach (string key in stats. Keys)
{
StatsArray. Add (key );
Hashtable values = (Hashtable) stats [key];
Foreach (string key2 in values. Keys)
{
StatsArray. Add (key2 + ":" + values [key2]);
}
}
Return statsArray;
}

MemCachedClient. Stats
Code
Copy codeThe Code is as follows:
Public Hashtable Stats (ArrayList servers, string command)
{
// Get SockIOPool instance
SockIOPool pool = SockIOPool. GetInstance (_ poolName );
// Return false if unable to get SockIO obj
If (pool = null)
{
// If (log. IsErrorEnabled)
//{
// Log. Error (GetLocalizedString ("unable to get socket pool "));
//}
Return null;
}
// Get all servers and iterate over them
If (servers = null)
Servers = pool. Servers;
// If no servers, then return early
If (servers = null | servers. Count <= 0)
{
// If (log. IsErrorEnabled)
//{
// Log. Error (GetLocalizedString ("stats no servers "));
//}
Return null;
}
// Array of stats Hashtables
Hashtable statsMaps = new Hashtable ();
For (int I = 0; I <servers. Count; I ++)
{
SockIO sock = pool. GetConnection (string) servers [I]);
If (sock = null)
{
// If (log. IsErrorEnabled)
//{
// Log. Error (GetLocalizedString ("unable to connect"). Replace ("$ Server $", servers [I]. ToString ()));
//}
Continue;
}
// Build command
Command = Discuz. Common. Utils. StrIsNullOrEmpty (command )? "Stats \ r \ n": command + "\ r \ n ";
Try
{
Sock. Write (UTF8Encoding. UTF8.GetBytes (command ));
Sock. Flush ();
// Map to hold key value pairs
Hashtable stats = new Hashtable ();
// Loop over results
While (true)
{
String line = sock. ReadLine ();
// If (log. IsDebugEnabled)
//{
// Log. Debug (GetLocalizedString ("stats line"). Replace ("$ Line $", line ));
//}
If (line. StartsWith (STATS ))
{
String [] info = line. Split ('');
String key = info [1];
String val = info [2];
// If (log. IsDebugEnabled)
//{
// Log. debug (GetLocalizedString ("stats success "). replace ("$ Key $", key ). replace ("$ Value $", val ));
//}
Stats [key] = val;
}
Else if (END = line)
{
// Finish when we get end from server
// If (log. IsDebugEnabled)
//{
// Log. Debug (GetLocalizedString ("stats finished "));
//}
Break;
}
StatsMaps [servers [I] = stats;
}
}
Catch // (IOException e)
{
// If (log. IsErrorEnabled)
//{
// Log. Error (GetLocalizedString ("stats IOException"), e );
//}
Try
{
Sock. TrueClose ();
}
Catch // (IOException)
{
// If (log. IsErrorEnabled)
//{
// Log. Error (GetLocalizedString ("failed to close some socket"). Replace ("$ Socket $", sock. ToString ()));
//}
}
Sock = null;
}
If (sock! = Null)
Sock. Close ();
}
Return statsMaps;
}

With these two methods, we can get the cache items in memcached.
The basic idea is to first obtain all the items (stats items) in the cache, and then retrieve the cachekey and cachevalue (stats cachedump) using the itemid)
The program implementation is as follows:
Copy codeThe Code is as follows:
Private void GetItems ()
{
ArrayList itemarr = new ArrayList ();
ArrayList arrayList = new ArrayList ();
StringBuilder sb = new StringBuilder ();
Foreach (string server in MemCachedManager. ServerList)
{
ArrayList. Add (server );
}
ArrayList arr = MemCachedManager. GetStats (arrayList, MemCachedManager. Stats. Items, null );
Foreach (string a in arr)
{
String [] tmparr = a. Split (':');
If (tmparr. Length> 1)
{
Int item_id = 0;
Int. TryParse (tmparr [1], out item_id );
Bool find = false;
Foreach (int item in itemarr)
{
If (item = item_id)
Find = true;
}
If (! Find & item_id> 0 & item_id! = 11211)
Itemarr. Add (item_id );
}
}
Foreach (int item in itemarr)
{
Sb. Append ("item" + item + "<br/> ");
ArrayList cachearr = MemCachedManager. GetStats (arrayList, MemCachedManager. Stats. CachedDump, "" + item + "10 ");
Foreach (string cache in cachearr)
{
Sb. Append (cache );
Sb. Append ("<br/> ");
}
}
Response. Write (sb. ToString ());
}

Run the program:

Why is no cache output?

Bug in DiscuzNT3.0

So I found it was caused by a bug in DiscuzNT3.0.

In MemCachedClient. Stats, there is such a piece of code:
Copy codeThe Code is as follows:
If (line. StartsWith (STATS ))
{
String [] info = line. Split ('');
String key = info [1];
String val = info [2];
Stats [key] = val;

}
Else if (END = line)
{
Break;
}

It turns out that the results of stats cachedump are ignored and start with ITEM, so nothing is output. A few simple modifications:
Copy codeThe Code is as follows:
If (line. StartsWith (STATS ))
{
String [] info = line. Split ('');
String key = info [1];
String val = info [2];
Stats [key] = val;

}
Else if (line. StartsWith ("ITEM "))
{
String [] info = line. Split ('[');
String key = info [0]. Split ('') [1];
String val = "[" + info [1];

Stats [key] = val;
}
Else if (END = line)
{
Break;
}

The output result is displayed normally.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.