public void Set <T>(string key, T value) { key = preFix + key; string sessionId = GetSessionId(); if (string.IsNullOrEmpty(sessionId)) { sessionId = SetSessionId(); } //TODO 这里高并发时,同一个sessionid的dict可能会被相互覆盖,有时间必须重写加锁 object cachedItem = mc.Get(sessionId); if (cachedItem == null) { Dictionary <string, object> dic = new Dictionary <string, object>(); dic[key] = value; mc.Set(sessionId, dic, DateTime.Now.AddHours(sessionHour)); } else { Dictionary <string, object> dic = cachedItem as Dictionary <string, object>; dic[key] = value; mc.Set(sessionId, dic, DateTime.Now.AddHours(sessionHour)); } }
/// <summary> /// 增加缓存项目 /// </summary> /// <param name="key">缓存键名</param> /// <param name="obj">缓存对象</param> public void Insert(string key, object obj) { if (obj != null) { mc.Set(key, obj); } }
//更多的是存储一个自定义的类的实例对象。这就需要使用到序列化,下面我们来新加一个类MyObject,让其作为可序列化的对象来存储进Memcached中 public void MemcachedTest(string[] args) { //初始化池 SockIOPool sock = SockIOPool.GetInstance(); sock.SetServers(serverlist.ToArray()); //添加服务器列表 sock.InitConnections = 3; //设置连接池初始数目 sock.MinConnections = 3; //设置最小连接数目 sock.MaxConnections = 5; //设置最大连接数目 sock.SocketConnectTimeout = 1000; //设置连接的套接字超时。 sock.SocketTimeout = 3000; //设置套接字超时读取 sock.MaintenanceSleep = 30; //设置维护线程运行的睡眠时间。如果设置为0,那么维护线程将不会启动; //获取或设置池的故障标志。 //如果这个标志被设置为true则socket连接失败, //将试图从另一台服务器返回一个套接字如果存在的话。 //如果设置为false,则得到一个套接字如果存在的话。否则返回NULL,如果它无法连接到请求的服务器。 sock.Failover = true; //如果为false,对所有创建的套接字关闭Nagle的算法。 sock.Nagle = false; sock.Initialize(); MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = true; //是否启用压缩数据 //mc.Set(key,val);//设置 键值 //mc.KeyExists(key) //键 是否存 //mc.Get(key) //获取 一个键值 //mc.Delete(key);// 删除 键值 Console.WriteLine("----------------------------Set-----------"); mc.Set("key1", "value1"); Console.WriteLine(mc.Get("key1")); Console.WriteLine("---------------------------replay---------"); mc.Replace("key1", "Replay new Key1"); Console.WriteLine(mc.Get("key1")); Console.WriteLine("---------------------------键值是否存在----"); if (mc.KeyExists("key2")) { Console.WriteLine("key2存在"); } else { Console.WriteLine("key2不存在,设置新值"); mc.Set("key2", "New key2"); } Console.WriteLine("-------------------------删除数据--------"); mc.Delete("key2"); Console.WriteLine("删除之后的数据: " + mc.Get("key2")); Console.WriteLine("-------------------------数据过期--------"); mc.Add("key3", "新数据三内容", DateTime.Now.AddMilliseconds(5000)); Console.WriteLine(mc.Get("key5")); System.Threading.Thread.Sleep(6000); Console.WriteLine("过期: " + mc.Get("key5")); Console.ReadLine(); }
/// <summary> /// 设置缓存数据 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间</param> /// <returns></returns> public static bool SetCache(string key, object value, DateTime?expiry = null) { if (expiry == null) { return(mclient.Set(key, value)); } return(mclient.Set(key, value, expiry.Value)); }
/// <summary> /// 添加缓存信息(如果存在缓存信息则直接重写设置,否则添加) /// 使用:MemcacheHelper.GetInstance().Add(key,value) /// </summary> /// <param name="key">需要缓存的键</param> /// <param name="value">需要缓存的值</param> public void Add(string key, object value) { if (_client.KeyExists(key)) { _client.Set(key, value); } _client.Add(key, value); }
public void TestBulkGet(MemcachedClient c) { c.Set("test1", "test1_key"); c.Set("test3", "test3_key"); var res = c.Get(new string[] { "test1", "test2", "test3" }); CollectionAssert.AreEquivalent(new String[] { "test1_key", null, "test3_key" }, res); }
/// <summary> /// Places an item in the cache. /// </summary> /// <param name="key">The key of the object.</param> /// <param name="value">The cached object.</param> public void Set(object key, object value) { if (key == null) { throw new ArgumentNullException("key"); } _client.Set(GetCacheKey(key), value); }
private void _Set <T>(string key, T value) { if (value == null) { mc.Delete(key); } else { mc.Set(key, value); } }
/// <summary> /// /// </summary> /// <param name="value">值</param> /// <param name="time">过期时间</param> /// <returns>SessionId</returns> public static string Set(object value, DateTime time) { string key = Guid.NewGuid().ToString(); bool rst = mc.Set(key, value, time); if (rst == false) { return(""); } return(key); }
public void Add(string key, object value, bool isExpiration = true) { mc = MemcachedClient.GetInstance(CacheName); if (isExpiration) { mc.Set(key, value, DefaultExpirationTime); } else { mc.Set(key, value); } }
/// <summary> /// Stores the specified value associated to the identifier object. /// </summary> /// <param name = "data"></param> /// <param name = "key"></param> /// <param name = "value"></param> public static void Store(this IDataIdentify data, String key, Object value) { try { var translatedKey = data.TranslateKey(key); DefaultCache.Set(translatedKey, value); } catch (Exception e) { STrace.Exception(typeof(LogicCache).FullName, e); } }
public string SaveFileSegment(byte[] buffer, string companyID, string fileName, int fileLength, int totalSegments, int currentSegmentsIndex) { string segKey = string.Format("{0}_{1}_{2}_{3}_{4}_{5}", _Key, companyID, fileName, fileLength, totalSegments, currentSegmentsIndex); try { _mc.Set(segKey, buffer, DateTime.Now.AddHours(1)); return(""); } catch (Exception e) { return(e.Message); } }
/// <summary> /// 写入memcached /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> /// <param name="expiry">过期时间(如:DateTime.Now.AddMinutes(1))</param> /// <returns></returns> public static bool Set(string key, Object value, DateTime expiry) { if (!checkKey(key)) { return(false); } //初始化池 SetPool(); objMC.PoolName = poolName; objMC.EnableCompression = false; return(objMC.Set(key, value, expiry)); }
public bool SetDefineMenu(string companyID, List <DefineMenu> list) { bool result = true; try { _mc.Set(_Key + companyID.Trim() + "_DefineMenu", list); } catch { result = false; } return(result); }
/// <summary> /// 更新缓存信息 /// </summary> /// <param name="objId"></param> /// <param name="o"></param> public static bool SetObject(string objId, object o, int expiry = 0) { MemcachedClient tmp = GetClient(); bool bRes = false; if (expiry > 0) { bRes = tmp.Set(objId, o, DateTime.Now.AddSeconds(expiry)); } else { bRes = tmp.Set(objId, o); } return(bRes); }
public void Update(string groupName, string key, object value) { MemcachedClient client = GetMemcachedClient(groupName); RemoteCachePolicy policy = cacheSettingManager.GetRemoteCachePolicy(groupName); if (policy != null && policy.AbsoluteExpirationTimeInSecond > 0) { client.Set(key, value, DateTime.Now.AddSeconds(policy.AbsoluteExpirationTimeInSecond)); } else { client.Set(key, value); } }
//9.Get test public void GetTest() { MemcachedClient cache = MemcachedClient.GetInstance("BeITMemcached"); cache.Set("liyanze", "Work harder, play happier!", 4711); HandleLogs("[Cmd=Get]liyanze:" + cache.Get("liyanze")); }
//14.Set test public void SetTest() { MemcachedClient cache = MemcachedClient.GetInstance("BeITMemcached"); cache.Set("BeIt", "happy"); HandleLogs("[Cmd=Set]BeIt:" + cache.Get("BeIt").ToString()); }
/// <summary> /// 覆盖缓存 /// </summary> /// <param name="pKey"></param> /// <param name="pObject"></param> /// <returns></returns> private static bool StoreCache(string pKey, object pObject) { MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = true; bool _result = false; if (IsCache(mc, pKey)) { if (mc.Get(pKey) == null) { mc.Set(pKey, pObject);//缓存存在,强行覆盖 } else { mc.Replace(pKey, pObject);//缓存存在,强行覆盖 } _result = true; } else { mc.Add(pKey, pObject);//第一次加载缓存 _result = true; } return(_result); }
public string SetWxToken() { var token = AllFunc.Instance.GetWXToken(); cache.Set("WxToken", token, DateTime.Now.AddMinutes(110)); return(token); }
static void Main(string[] args) { string[] servidores = { "127.0.0.1:11211" }; SockIOPool pool = SockIOPool.GetInstance(); pool.SetServers(servidores); pool.Initialize(); var cache = new MemcachedClient(); string chave = "dados"; string retorno = ""; if (cache.KeyExists(chave)) { retorno = cache.Get(chave).ToString(); } else { cache.Set(chave, DateTime.Now.ToString(), DateTime.Now.AddMinutes(1)); retorno = "primeiro acesso ao cache"; } Console.WriteLine(retorno); Console.Read(); }
public void SetAll <T>(string cacheid, IEnumerable <string> keys, IEnumerable <T> values, int duration = 0) { if (keys != null && values != null && keys.Count() == values.Count()) { var prefixedKeys = Key(cacheid, keys); IDictionary <string, T> dictionary = new Dictionary <string, T>(); IEnumerator <T> valuesEnumerator = values.GetEnumerator(); foreach (string key in prefixedKeys) { if (valuesEnumerator.MoveNext()) { _cache.Set(key, valuesEnumerator.Current, TimeSpan.FromMinutes(duration)); } } } }
public void GetMultipleArray() { MemcachedClient mc = new MemcachedClient(); mc.Set("GetMultiple1", "GetMultipleValue1"); mc.Set("GetMultiple2", "GetMultipleValue2"); string[] keys = { "GetMultiple1", "GetMultiple2" }; object[] obj = mc.GetMultipleArray(keys); for (int i = 0; i < obj.Length; i++) { if (obj[i] != null) { HandleLogs("[Cmd=GetMultipleArray]GetMultipleArray value的值是:" + obj[i].ToString()); } } }
public void Put(object key, object value) { if (key == null) { throw new ArgumentNullException("key", "null key not allowed"); } if (value == null) { throw new ArgumentNullException("value", "null value not allowed"); } if (log.IsDebugEnabled) { log.DebugFormat("setting value for item {0}", key); } bool returnOk = client.Set(KeyAsString(key), new DictionaryEntry(GetAlternateKeyHash(key), value), DateTime.Now.AddSeconds(expiry)); if (!returnOk) { if (log.IsWarnEnabled) { log.WarnFormat("could not save: {0} => {1}", key, value); } } }
static void Main(string[] args) { //就是构建了一个集群 安装memcached 的使用 我们是一个客户端使用 //在实际项目中使用 可以在哪些地方使用 有一个唯一的KeyValue 来获取一个单独的数据 //项目中玩耍的东西。。 string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" }; //初始化池 SockIOPool pool = SockIOPool.GetInstance(); pool.SetServers(serverlist); pool.InitConnections = 3; pool.MinConnections = 3; pool.MaxConnections = 5; pool.SocketConnectTimeout = 1000; pool.SocketTimeout = 3000; pool.MaintenanceSleep = 30; pool.Failover = true; pool.Nagle = false; pool.Initialize(); // 获得客户端实例 MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = false; Console.WriteLine("------------测 试-----------"); mc.Set("test", "my value"); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test" if (mc.KeyExists("test")) //测试缓存存在key为test的项目 { Console.WriteLine("test is Exists"); Console.WriteLine(mc.Get("test").ToString()); //在缓存中获取key为test的项目 } else { Console.WriteLine("test not Exists"); } Console.ReadLine(); mc.Delete("test"); //移除缓存中key为test的项目 if (mc.KeyExists("test")) { Console.WriteLine("test is Exists"); Console.WriteLine(mc.Get("test").ToString()); } else { Console.WriteLine("test not Exists"); } Console.ReadLine(); SockIOPool.GetInstance().Shutdown(); //关闭池, 关闭sockets }
public static void MemCache() { InitMemcache(); MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = false; DisplayMenu(); while (true) { string selected = Console.ReadLine(); switch (selected) { case "1": mc.Set("test", "my value"); break; case "2": if (mc.KeyExists("test")) { Console.WriteLine(mc.Get("test").ToString()); } else { Console.WriteLine("it not exists test"); } break; default: break; } } }
/// <summary> /// @brief:以键值Key保存类型为string的value数据 /// </summary> /// <param name="poolName"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="liveSecs"></param> /// <param name="compress"></param> /// <returns></returns> public static bool Set(string poolName, string key, string value, int liveSecs = UnExpired, bool compress = false) { try { if (liveSecs < 0) { return(false); } if (liveSecs == 0) { liveSecs = UnExpired; } DateTime expired = DateTime.Now.AddSeconds(liveSecs); MemcachedClient mc = MemcacheItem.GetInstance(poolName); mc.PoolName = poolName; mc.EnableCompression = compress; return(mc.Set(key, value, expired)); } catch (Exception ex) { LogEngine.Write(LOGTYPE.ERROR, "MemcacheItem Set ex:", ex.ToString()); return(false); } }
static void Main(string[] args) { string[] serverList = { "192.168.1.120:11211", "10.0.0.137:11211" }; //初始化池 SockIOPool pool = SockIOPool.GetInstance(); pool.SetServers(serverList); pool.InitConnections = 3; pool.MinConnections = 3; pool.MaxConnections = 5; pool.SocketConnectTimeout = 1000; pool.SocketTimeout = 3000; pool.MaintenanceSleep = 30; pool.Failover = true; pool.Nagle = false; pool.Initialize(); //获得客户端实例 MemcachedClient mc = new MemcachedClient(); mc.EnableCompression = false; Console.WriteLine("------------测 试-----------"); string key = "test"; mc.Set(key, "my value"); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test" if (mc.KeyExists(key)) { Console.WriteLine("test is Exists"); Console.WriteLine(mc.Get("test").ToString()); //在缓存中获取key为test的项目 } else { Console.WriteLine("test not Exists"); } Console.ReadLine(); //移除缓存中key为test的项目 mc.Delete(key); if (mc.KeyExists(key)) { Console.WriteLine("test is Exists"); Console.WriteLine(mc.Get("test").ToString()); } else { Console.WriteLine("test not Exists"); } Console.ReadLine(); //关闭池, 关闭sockets SockIOPool.GetInstance().Shutdown(); }
//3.CheckAndSet test public void CheckAndSetTest() { MemcachedClient cache = MemcachedClient.GetInstance("BeITMemcached"); cache.Set("castest", "a"); //Trying to CAS key castest with the wrong unique HandleLogs("[Cmd=CheckAndSet]castest:" + cache.CheckAndSet("castest", "a", 0)); }
public void TestBasicDelete(MemcachedClient c) { Assert.IsNull(c.Get("test")); Assert.IsTrue(c.Set("test", "OKAY")); Assert.IsNotNull(c.Get("test")); Assert.IsTrue(c.Delete("test")); Assert.IsNull(c.Get("test")); }
public static bool LoadQueryInMemCached(MemcachedLoaderConfig Config, CachedQuery QueryToLoad, out string ErrorMessage) { bool LoadedQuery = false; ErrorMessage = string.Empty; ResponseCode response = ResponseCode.UnknownCommand; Dictionary<string, Dictionary<string, string>> MemoryDict; try { /* * Connect to memcached server */ ServerConnectionCollection MemCachedServers = new ServerConnectionCollection(); /* * Add Server from Config Settings */ MemCachedServers.Add(Config.MemcachedConnectionSettings.Server, port: Config.MemcachedConnectionSettings.Port); /* * Create the client */ IConnectionProvider provider = new ConnectionProvider(MemCachedServers); MemcachedClient client = new MemcachedClient(provider); /* * Retrieve Query Data from MySql */ DataTable QueryDataTable = GetDataTable(Config.DBConnectionSettings, QueryToLoad); /* * Determine whether to permanently persist kvp cached object in Redis */ bool PersistCachedObject = (Config.MemcachedConnectionSettings.CacheObjectSeconds <= 0); /* * Cache each row from the data table as a JSON serialized dictionary */ if (QueryDataTable != null && QueryDataTable.Rows.Count > 0) { //Define a dictionary to store the data table to be serialized into a JSON object MemoryDict = null; string ErrMsg = string.Empty; /* * Convert DataTable / MySQL Query ResultSet in Dictionary<string,Dictionary<string,string>> object */ bool Success = Utils.GetQueryCacheDictionaryFromDataTable(Config.DBConnectionSettings, QueryToLoad, QueryDataTable, out MemoryDict, out ErrMsg); /* * Table Data Dictionary was successfully created - Cached each row in Memcached as a JSON dictionary */ if (Success) { foreach (KeyValuePair<string, Dictionary<string, string>> TableDictionaryKvp in MemoryDict) { string Key = TableDictionaryKvp.Key; string JsonStoreValue = JsonConvert.SerializeObject(TableDictionaryKvp.Value, new KeyValuePairConverter()); /* * Determine right expiration Datetime value */ DateTime ExpireDate = (PersistCachedObject) ? DateTime.MaxValue : DateTime.Now.AddSeconds(Config.MemcachedConnectionSettings.CacheObjectSeconds); /* * Load Kvp in Memcached */ response = client.Set(Key, JsonStoreValue, ExpireDate); /* * If key already exists replace it */ if (response == ResponseCode.KeyExists) { response = client.Replace(Key, JsonStoreValue, ExpireDate); } } } } /* * Success */ LoadedQuery = (response == ResponseCode.NoError); Utils.GetEventLog().WriteEntry(string.Format("[MemcachedLoaderService.Memcached] Successfully loaded table [{0}] in the memory cache.", QueryToLoad.KeyPrefix)); } catch (Exception ex) { ErrorMessage = string.Format("[MemcachedLoaderService.Memcached] Can't load query into Cache. Memcached Error Message [{0}].", ex.Message); Utils.GetEventLog().WriteEntry(ErrorMessage); } /* * Results */ return LoadedQuery; }