Memcached 简单应用
时间:2011-03-21 来源:ryanSun
需要引用的 log4net.dll,Memcached.ClientLibrary.dll
添加类MemcachedTools.cs
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Memcached.ClientLibrary;
using System.Collections;
using System.Threading;
/// <summary>
///MemcachedTools 的摘要说明
/// </summary>
public class MemcachedTools
{
// <add key="newsMemcache" value="127.0.0.1:11211" />
//<add key="hqMemecache" value="172.28.1.27:11211" />
static MemcachedTools()
{
String[] serverlist = {"127.0.0.1:11211"};
SockIOPool pool = SockIOPool.GetInstance("news");
pool.SetServers(serverlist);
pool.Initialize();
}
/// <summary>
///
/// </summary>
private static MemcachedClient NewsClient
{
get
{
MemcachedClient mc = new MemcachedClient();
mc.PoolName = "news";
mc.EnableCompression = false;
return mc;
}
}
/// <summary>
/// 添加一个缓存
/// </summary>
/// <param name="obj">缓存对象</param>
/// <param name="sj">缓存时间</param>
public static void Add(string key, object obj, DateTime expiry)
{
if (!NewsClient.Add(key, obj, expiry))
{
NewsClient.Set(key, obj, expiry);
}
}
public static object GetHangqing(string key)
{
object obj = NewsClient.Get(key);
return obj;
}
public static string GetHangqingStr(string key)
{
string data = (string)NewsClient.Get(key);
return data;
}
public static object[] GetHangqing(string[] keys)
{
object[] objs = NewsClient.GetMultipleArray(keys);
return objs;
}
public static Hashtable GetHangqingHash(string[] keys)
{
Hashtable ht = NewsClient.GetMultiple(keys);
return ht;
}
}
页面方法引用:
//linq读取json格式
public string Dbval()
{
StringBuilder Json = new StringBuilder();
//var Myjson={"bindings"};
foreach (Service_help_special c in dcont.Service_help_special)
{
Json.Append("{specialid:" + c.specialid + ",content:" + c.content + ",infotitle:"+ c.infotitle +",infoid:"+ c.infoId +"}");
//mstring.Append(c.specialid + ":" + c.content + "," + c.infotitle + "," + c.infoId + "&");
}
return Json.ToString();
}
//添加内容到Memcache
protected void Button1_Click(object sender, EventArgs e)
{
MemcachedTools.Add("bb",Dbval(), DateTime.Now.AddHours(10));
Label1.Text = "";
}
//读取名称 为“bb”的Memcache
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = MemcachedTools.GetHangqingStr("bb");
}