using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Memcache;
namespace test.Controllers
{
public class MemcacheController : Controller
{
//
// GET: /Memcache/
public ActionResult Index()
{
return View();
}
/// <summary>
/// 测试date
/// </summary>
/// <returns></returns>
public ActionResult text()
{
string key = "123456";
string resultValue = GetCache("mes", key);
if (resultValue != null)
{
return View("text", resultValue);
}
ClawerDataService server = new ClawerDataService();
// List<ClawerDataModel> list = server.GetListArray();
TimeSpan expiry = TimeSpan.Parse("0000:0059:0059.0099");
string str = "dsdsdsdsd";
SetCache("mes", expiry, key, str);
return View("text", str);
}
/// <summary>
/// 根据cachename与key值获取缓存数据
/// </summary>
/// <param name="cacheName">缓存名称</param>
/// <param name="key">key</param>
/// <returns>缓存数据</returns>
private string GetCache(string cacheName, string key)
{
string result = null;
//服务器端ip
string[] servers = new string[] { "" };
string m_memCacheName = cacheName;
MemcachedClient cache = null;
//根据CacheName判断cached是否存在
if (!MemcachedClient.Exists(m_memCacheName))
{
//名称存抛出异常
MemcachedClient.Setup(m_memCacheName, servers);
}
//获取实例
cache = MemcachedClient.GetInstance(m_memCacheName);
//string key = commonParameter.MakeKey();
key = cacheName + key;
key = key.Replace(" ", "");
//根据key值获取我的缓存数据
var v = cache.Get(key);
if (v != null)
{
result = v.ToString();
}
return result;
}
/// <summary>
/// 将数据放到缓存里面
/// </summary>
/// <param name="cacheName">缓存名称</param>
/// <param name="expiry">存放时间</param>
/// <param name="key">key值</param>
/// <param name="value">我要缓存的东西</param>
private void SetCache(string cacheName, TimeSpan expiry, string key, string value)
{
//MemcachedClient的服务器端地址
string[] servers = new string[] { "" };
string m_memCacheName = cacheName;
MemcachedClient cache = null;
if (!MemcachedClient.Exists(m_memCacheName))
{
MemcachedClient.Setup(m_memCacheName, servers);
}
cache = MemcachedClient.GetInstance(m_memCacheName);
//string key = commonParameter.MakeKey();
//TimeSpan expiry = TimeSpan.Parse("0000:0059:0059.0099");
key = cacheName + key;
key = key.Replace(" ", "");
var v = cache.Get(key);
if (v != null)
{
cache.Delete(key);
cache.Set(key, value, expiry);
}
else
{
cache.Set(key, value, expiry);
}
}
}
}