Пример #1
2
 public void NullCache() {
     using (MemcachedClient client = new MemcachedClient("enyim.com/memcached")) {
         String key = Guid.NewGuid().ToString("n");
         Object value = null;
         client.Store(StoreMode.Set, key, value);
         var exist = client.TryGet(key, out value);
         Assert.IsTrue(exist);
         Assert.IsNull(value);
     }
 }
Пример #2
0
        static void testMemcachedProviders()  
        {
            MemcachedClient client = new MemcachedClient("enyim.com/memcached");
            //存值  --不带过期时间的存储,Memcached将根据LRU来决定过期策略  
            bool result = client.Store(Enyim.Caching.Memcached.StoreMode.Add, "name", "dinglang");
            
            //带过期时间的缓存    
            //bool success = client.Store(StoreMode.Add, person.UserName, person, DateTime.Now.AddMinutes(10));   
            if (result)
            {
                Console.Write("成功存入缓存");

                //取值    
                object name = client.Get("name");
                if (name != null)
                {
                    Console.Write("取出的值为:" + name);
                }
                else
                {
                    Console.Write("取值失败");
                }
            }
            else
            {
                Console.Write("存入缓存失败");
            }
        }    
Пример #3
0
		public void TestFixtureSetUp()
		{
			hasher = new SHA1Hasher();
			instances = new MemcachedInstances(100, Common.Properties.MainCacheServerIPEndPoints);
			mc = new MemcachedClient(instances, hasher);
			
		}
Пример #4
0
        public void TestThem(List<string> servers)
        {
            var mbc = new MemcachedClientConfiguration();
            foreach (var server in servers)
            {
                IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(server), 11211);
                mbc.Servers.Add(endPoint);
            }

            _couchbaseClient = new MemcachedClient(mbc);

            _couchbaseClient.Store(StoreMode.Set, Key, Value);
            Debug.Assert((string)_couchbaseClient.Get(Key) == Value);

            List<Thread> workers = new List<Thread>();

            for (int s = 0; s < NumThreads; s++)
            {
                Thread workerThread = new Thread(Run);
                workerThread.Start();
                workers.Add(workerThread);
            }

            foreach (var thread in workers)
            {
                while (thread.IsAlive)
                {
                    Thread.Sleep(1);
                }

                thread.Join();
            }
        }
Пример #5
0
		public void TestThrottlingFailurePolicy()
		{
			var config = new MemcachedClientConfiguration();
			config.AddServer("nonexisting.enyim.com:2244");

			config.SocketPool.FailurePolicyFactory = new ThrottlingFailurePolicyFactory(4, TimeSpan.FromMilliseconds(2000));
			config.SocketPool.ConnectionTimeout = TimeSpan.FromMilliseconds(10);
			config.SocketPool.ReceiveTimeout = TimeSpan.FromMilliseconds(10);
			config.SocketPool.MinPoolSize = 1;
			config.SocketPool.MaxPoolSize = 1;

			var client = new MemcachedClient(config);
			var canFail = false;
			var didFail = false;

			client.NodeFailed += node =>
			{
				Assert.IsTrue(canFail, "canfail");

				didFail = true;
			};

			Assert.IsNull(client.Get("a"), "Get should have failed. 1");
			Assert.IsNull(client.Get("a"), "Get should have failed. 2");

			canFail = true;
			Thread.Sleep(2000);

			Assert.IsNull(client.Get("a"), "Get should have failed. 3");
			Assert.IsNull(client.Get("a"), "Get should have failed. 4");
			Assert.IsNull(client.Get("a"), "Get should have failed. 5");
			Assert.IsNull(client.Get("a"), "Get should have failed. 6");

			Assert.IsTrue(didFail, "didfail");
		}
		public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}
			if (string.IsNullOrEmpty(name))
			{
				name = "MemcachedProviders.CacheProvider";
			}
			if (string.IsNullOrEmpty(config["description"]))
			{
				config.Remove("description");
				config.Add("description", "Memcached Cache Provider");
			}

			base.Initialize(name, config);

			if (String.IsNullOrEmpty(config["section"]))
			{
				throw new ArgumentException("未配置 section 属性。");
			}

			IMemcachedClientConfiguration section = (IMemcachedClientConfiguration)this.Configuration.GetSection(config["section"]);
			if (section == null)
			{
				throw new ConfigurationErrorsException(String.Format("未找到适用于 MemcachedDistributeCacheProvider 的配置节 {0}", config["section"]));
			}

			this.client = new CustomMemcachedClient(section);
		}
        public void SetUp()
        {
            var config = new MemcachedClientConfiguration();
            config.AddServer("127.0.0.1", 11211);

            _Client = new MemcachedClient(config);
        }
        protected override MemcachedClient GetClient()
        {
            MemcachedClient client = new MemcachedClient("test/binaryConfig");
            client.FlushAll();

            return client;
        }
Пример #9
0
 /// <summary>
 /// 添加缓存(键不存在则添加,存在则替换)
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="minutes">缓存时间(分钟)</param>
 /// <returns></returns>
 public static bool AddCache(string key, object value, int minutes)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Store(StoreMode.Set, key, value, DateTime.Now.AddMinutes(minutes));
     }
 }
Пример #10
0
 /// <summary>
 /// 添加缓存(键不存在则添加,存在则替换)
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <returns></returns>
 public static bool AddCache(string key, object value)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Store(StoreMode.Set, key, value);
     }
 }
Пример #11
0
 /// <summary>
 /// 获取缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <returns>返回缓存,没有找到则返回null</returns>
 public static object GetCache(string key)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Get(key);
     }
 }
Пример #12
0
        public void StoreWithProtoTranscoder()
        {
            var config = GetConfig();
            var transcoder = new ProtoBuf.Caching.Enyim.NetTranscoder();
            config.Transcoder =  transcoder;
            SomeType obj = new SomeType { Id = 1, Name = "abc" }, clone;
            string cloneString;
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(0, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                client.Store(StoreMode.Set, "raw1", obj);
                client.Store(StoreMode.Set, "raw2", "def");
            }
            Assert.AreEqual(0, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);
            using (var client = new MemcachedClient(config))
            {
                clone = (SomeType)client.Get("raw1");
                cloneString = (string)client.Get("raw2");
            }
            Assert.AreEqual(1, transcoder.Deserialized);
            Assert.AreEqual(1, transcoder.Serialized);

            Assert.AreEqual(1, clone.Id);
            Assert.AreEqual("abc", clone.Name);
            Assert.AreEqual("def", cloneString);
        }
Пример #13
0
 /// <summary>
 /// 是否存在该缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <returns></returns>
 public static bool IsExists(string key)
 {
     using (MemcachedClient mc = new MemcachedClient())
     {
         return mc.Get(key) != null;
     }
 }
        public ElasticacheClient(string regionName, IDictionary<string, string> properties, MemcachedClient memcachedClient)
        {
            _region = regionName;
            _client = memcachedClient;
            _expiry = 300;

            if (properties == null) return;

            var expirationString = GetExpirationString(properties);
            if (expirationString != null)
            {
                _expiry = Convert.ToInt32(expirationString);
                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat("using expiration of {0} seconds", _expiry);
                }
            }

            if (properties.ContainsKey("regionPrefix"))
            {
                _regionPrefix = properties["regionPrefix"];
                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat("new regionPrefix :{0}", _regionPrefix);
                }
            }
            else
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("no regionPrefix value given, using defaults");
                }
            }
        }
Пример #15
0
        public MemcachedLocker(MemcachedClient client, string key, TimeSpan timeOut)
        {
            this.client = client;
            this.key = key;
            this.timeOut = timeOut;

            int sleep = 10;
            DateTime now = DateTime.Now;
            while (DateTime.Now - now < timeOut)
            {
                if (client.Add<DateTime?>(key, DateTime.Now.Add(timeOut)))
                    return;

                //需要排除锁未释放的可能,如果检测到超过超时时间2倍的话,尝试获得锁
                ulong version;
                var time = client.Get<DateTime?>(key, out version);
                if (time == null || (time.HasValue && time.Value.ToLocalTime().Add(timeOut + timeOut) < DateTime.Now))
                {
                    LocalLoggingService.Warning("{0} {1} {2} {3}", DistributedServerConfiguration.ModuleName, "MemcachedLocker", "MemcachedLocker",
                                        string.Format("发现一个超时的分布式锁,超时时间:{0} Key : {1}",
                                        time, key));
                    if (client.Add<DateTime?>(key, DateTime.Now.Add(timeOut), version))
                        return;
                }

                if (sleep < 1000)
                    sleep = sleep * 110 / 100;
                else
                    sleep = 1000;

                Thread.Sleep(sleep);
            }

            throw new TimeoutException(string.Format("获得锁的时间超过了设定的最大时间 {0}", timeOut.ToString()));
        }
Пример #16
0
        public void ConfigurationTest() {
            using(var client = new MemcachedClient()) {
                client.ShouldNotBeNull("client");

                //client.Cas(StoreMode.Set, "item1", 1);
                //client.Cas(StoreMode.Set, "item2", 2);
            }
        }
        public void DecrementTest()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.Store(StoreMode.Set, "VALUE", "100");

            Assert.AreEqual(98L, mc.Decrement("VALUE", 2));
            Assert.AreEqual(88L, mc.Decrement("VALUE", 10));
        }
Пример #18
0
 public static void Initialize(Enyim.Caching.Configuration.MemcachedClientConfiguration config)
 {
     if (client != null)
     {
         throw new Exception("MemcachedClient has already been initialized");
     }
     client = new MemcachedClient(config);
 }
 public void Stop()
 {
     lock (_syncObject)
     {
         _clientInstance.Dispose();
         _clientInstance = null;
     }
 }
Пример #20
0
 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         Log.Debug("MemcachedCache.Initialise - initialising");
         _cache = new MemcachedClient();
     }
 }
Пример #21
0
		internal MemcachedDistributeCache(MemcachedClient client, string cacheName, string regionName, TimeSpan asyncTimeToLive, TimeSpan asyncUpdateInterval)
		{
			this.client = client;
			this.cacheName = cacheName;
			this.regionName = regionName;

			this.asyncTimeToLive = asyncTimeToLive;
			this.asyncUpdateInterval = asyncUpdateInterval;
		}
Пример #22
0
 /// <summary>
 /// 创建Memcached
 /// </summary>
 /// <returns></returns>
 private static MemcachedClient ResetMemcached()
 {
     if (memcached != null) { memcached = null; }
     memcached = MemcachedClient.GetInstance();
     memcached.SendReceiveTimeout = 5000;
     memcached.MaxPoolSize = 1000;
     memcached.MinPoolSize = 10;
     return memcached;
 }
Пример #23
0
 public MemcacheCacheProvider(string cacheName, string[] cacheServers)
     : base()
 {
     locker = new object();
     cache_name = cacheName;
     cache_servers = cacheServers;
     config = null;
     client = null;
 }
Пример #24
0
        public void CanCacheString()
        {
            var client = new MemcachedClient();

            client.Store(StoreMode.Add, "a", "b");
            var result = client.Get<string>("a");

            Assert.AreEqual("b", result);
        }
        public void Start(IDictionary<string, string> properties)
        {
            // Needs to lock staticly because the pool and the internal maintenance thread
            // are both static, and I want them syncs between starts and stops.
            lock (_syncObject)
            {
                if (_clientInstance != null) return;

                _clientInstance = new MemcachedClient(new ElastiCacheClusterConfig());
            }
        }
Пример #26
0
        /// <summary>
        /// Contructor
        /// </summary>
        public MemCacheHelper()
        {
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();
            config.Servers.Add(GetIPEndPointFromHostName(MEMCACHE_HOST, MEMCACHE_PORT));
            config.Protocol = MemcachedProtocol.Binary;
            config.Authentication.Type = typeof(PlainTextAuthenticator);
            config.Authentication.Parameters["userName"] = "******";
            config.Authentication.Parameters["password"] = "******";
            config.Authentication.Parameters["zone"] = "";

            _mc = new MemcachedClient(config);
        }
Пример #27
0
        public void RunProgram()
        {
            const string key = "testkey";
            var cacheClient = new MemcachedClient(ConfigurationManager.GetSection("enyim.com/memcached") as IMemcachedClientConfiguration);
            cacheClient.Store(StoreMode.Add, key, "testvalue");
            var item = cacheClient.Get(key);
            Console.WriteLine(item);

            cacheClient.Store(StoreMode.Set, key, "something else");
            item = cacheClient.Get(key);
            Console.WriteLine(item);
        }
Пример #28
0
        public void CanCacheList()
        {
            var client = new MemcachedClient();
            var list = new List<string> { "a", "b" };

            client.Store(StoreMode.Set, "d", list);

            var result = client.Get<List<string>>("d");
            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("a", result[0]);
            Assert.AreEqual("b", result[1]);
        }
        static MemcachedContainerStrategy()
        {
            // //初始化memcache服务器池
            //SockIOPool pool = SockIOPool.GetInstance();
            ////设置Memcache池连接点服务器端。
            //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();

            //cache = new MemcachedClient();
            //cache.EnableCompression = false;
            try
            {
                //config.Authentication.Type = typeof(PlainTextAuthenticator);
                //config.Authentication.Parameters["userName"] = "******";
                //config.Authentication.Parameters["password"] = "******";
                //config.Authentication.Parameters["zone"] = "zone";//domain?   ——Jeffrey 2015.10.20
                DateTime dt1 = DateTime.Now;
                var config = GetMemcachedClientConfiguration();
                var cache = new MemcachedClient(config);

                var testKey = Guid.NewGuid().ToString();
                var testValue = Guid.NewGuid().ToString();
                cache.Store(StoreMode.Set, testKey, testValue);
                var storeValue = cache.Get(testKey);
                if (storeValue as string != testValue)
                {
                    throw new Exception("MemcachedStrategy失效,没有计入缓存!");
                }
                cache.Remove(testKey);
                DateTime dt2 = DateTime.Now;

                WeixinTrace.Log(string.Format("MemcachedStrategy正常启用,启动及测试耗时:{0}ms", (dt2 - dt1).TotalMilliseconds));
            }
            catch (Exception ex)
            {
                //TODO:记录是同日志
                WeixinTrace.Log(string.Format("MemcachedStrategy静态构造函数异常:{0}", ex.Message));
            }
        }
Пример #30
0
		public void TestIfCalled()
		{
			var config = new MemcachedClientConfiguration();
			config.AddServer("nonexisting.enyim.com:2244");

			config.SocketPool.FailurePolicyFactory = new FakePolicy();
			config.SocketPool.ConnectionTimeout = TimeSpan.FromSeconds(4);
			config.SocketPool.ReceiveTimeout = TimeSpan.FromSeconds(6);

			var client = new MemcachedClient(config);

			Assert.IsNull(client.Get("a"), "Get should have failed.");
		}
Пример #31
0
        /// <summary>
        /// 替换更新数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expiry">过期时间</param>
        /// <param name="hashCode"></param>
        public static void ReplaceFrom(string server, string key, object value, DateTime expiry, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            client.Replace(key, value, expiry, hashCode);
        }
Пример #32
0
        /// <summary>
        /// 删除指定条件缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="hashCode">哈希码</param>
        /// <param name="expiry">过期时间</param>
        public static bool DeleteFrom(string server, string key, int hashCode, DateTime expiry)
        {
            MemcachedClient client = GetClient(server);

            return(client.Delete(key, hashCode, expiry));
        }
Пример #33
0
        private static Dictionary <string, int> _serverlist;// = SiteConfig.MemcachedAddresss; TODO:全局注册配置

        #region 单例

        /// <summary>
        /// LocalCacheStrategy的构造函数
        /// </summary>
        MemcachedContainerStrategy()
        {
            _config = GetMemcachedClientConfiguration();
            _cache  = new MemcachedClient(_config);
        }
Пример #34
0
        /// <summary>
        ///  获取一个数值元素
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="hashCode">哈希码</param>
        /// <returns></returns>
        public static long GetCounterFrom(string server, string key, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            return(client.GetCounter(key, hashCode));
        }
Пример #35
0
        /// <summary>
        /// 减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static long DecrementFrom(string server, string key)
        {
            MemcachedClient client = GetClient(server);

            return(client.Decrement(key));
        }
Пример #36
0
        /// <summary>
        /// 从指定服务器获取
        /// </summary>
        /// <param name="server">服务器,Svr1,Svr2</param>
        /// <param name="key">键</param>
        /// <param name="hashCode">哈希码</param>
        public static object GetFrom(string server, string key, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            return(client.Get(key, hashCode));
        }
Пример #37
0
        /// <summary>
        ///  设置数据缓存
        /// </summary>
        /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="hashCode">哈希码</param>
        public static void SetTo(string server, string key, object value, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            client.Set(key, value, hashCode);
        }
Пример #38
0
        /// <summary>
        /// 批量读取数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="keys">键集合</param>
        public static object[] GetMultipleArrayFrom(string server, string[] keys)
        {
            MemcachedClient client = GetClient(server);

            return(client.GetMultipleArray(keys));
        }
Пример #39
0
 public MemcachedCache()
 {
     _mc = new MemcachedClient();
 }
Пример #40
0
 private static EnyimTableCache GetEnyimTableCache(MemcachedClient memcachedClient)
 {
     return(new EnyimTableCache(memcachedClient, TimeSpan.FromDays(1)));
 }
Пример #41
0
 private MemcachedClientService()
 {
     _client = new MemcachedClient("memcached");
 }
        public ActionResult AddItem(int idProducto, int cantidad)
        {
            if (!ModelState.IsValid)
            {
                return(View("Index"));
            }

            //consulto el usuario logueado
            var currentUser = System.Web.HttpContext.Current.User as CustomPrincipal;

            if (currentUser == null)
            {
                return(RedirectToAction("Index", "Account"));
            }

            var clientConfiguration = new MemcachedClientConfiguration {
                Protocol = MemcachedProtocol.Binary
            };

            clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 32769));

            using (var client = new MemcachedClient(clientConfiguration))
            {
                //consulto el cache del usuario logueado
                var cart = client.Get <Cart>("Cart-" + currentUser.UserName);

                var proxy = new ServiceProxyB2CClient();
                //var producto = proxy.ConsultarProducto(TipoConsultaProducto.ID, idProducto.ToString(), null, null).First();

                //No se porque el servicio de productos no devuelve datos.
                var producto = proxy.ConsultarCampaniaProducto().First();

                if (null == cart)
                {
                    //si el carrito es vacio cree uno nuevo
                    cart = new Cart
                    {
                        UserId = (int)currentUser.CustId,
                        Items  = new List <Item>()
                    };

                    var item = new Item
                    {
                        Producto = producto,
                        Cantidad = cantidad
                    };
                    cart.Items.Add(item);

                    client.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                }
                else
                {
                    foreach (var i in cart.Items.Where(i => i.Producto.id_producto == idProducto))
                    {
                        //Si existe un carrito busco el item y adiciono la cantidad
                        i.Cantidad = i.Cantidad + cantidad;
                        client.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                        return(View("cart", cart));
                    }

                    //si no existe el item en el carrito lo agrego a la coleccion y guardo el carro
                    var item = new Item
                    {
                        Producto = producto,
                        Cantidad = cantidad
                    };
                    cart.Items.Add(item);
                    client.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                }
                return(View("Cart", cart));
            }
        }
        public ActionResult Pagar()
        {
            if (!ModelState.IsValid)
            {
                return(View("Index"));
            }

            //consulto el usuario logueado
            var currentUser = System.Web.HttpContext.Current.User as CustomPrincipal;

            if (currentUser == null)
            {
                return(RedirectToAction("Index", "Account"));
            }

            var clientConfiguration = new MemcachedClientConfiguration {
                Protocol = MemcachedProtocol.Binary
            };

            clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 32769));
            ServiceProxyB2C.CrearOrdenResponse response = new ServiceProxyB2C.CrearOrdenResponse();
            using (var client = new MemcachedClient(clientConfiguration))
            {
                //consulto el cache del usuario logueado
                var cart = client.Get <Cart>("Cart-" + currentUser.UserName);

                if (cart != null)
                {
                    var proxy = new ServiceProxyB2CClient();

                    // se crea una nueva orden
                    Orden orden = new Orden();

                    // se deja el estado en validacion
                    orden.estatus     = EstatusOrden.VALIDACION;
                    orden.fecha_orden = DateTime.Now;

                    // se crea una nueva lista de items del carrito
                    List <ServiceProxyB2C.Item> lstitem = new List <ServiceProxyB2C.Item>();
                    foreach (Models.Item item in cart.Items)
                    {
                        ServiceProxyB2C.Item itemorden = new ServiceProxyB2C.Item();
                        itemorden.id_prod = item.Producto.id_producto;
                        // el servicio pide el nombre del producto, en el carrito no hay se coloca el nombre del espectaculo
                        itemorden.nombre_prod = item.Producto.espectaculo;

                        // en el servicio se pide el precio, se deja un valor fijo para ajustar modelo
                        itemorden.precio   = 100000;
                        itemorden.cantidad = item.Cantidad;
                        lstitem.Add(itemorden);
                    }
                    orden.item = lstitem.ToArray();

                    response = proxy.CrearOrdenes(orden);
                }
                else
                {
                    response.id_orden               = "";
                    response.estatus_orden          = EstatusOrden.RECHAZADA;
                    response.estatus_ordenSpecified = false;
                }
            }
            return(View("_Compra", response));
        }
Пример #44
0
 public MemcachedCacheProvider(MemcachedClient client)
 {
     this._client = client;
 }
Пример #45
0
        /// <summary>
        /// 批量读取数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="keys">键集合</param>
        /// <param name="hashCodes">哈希码集合</param>
        /// <param name="asString">所有值返回字符</param>
        public static Hashtable GetMultipleFrom(string server, string[] keys, int[] hashCodes, bool asString)
        {
            MemcachedClient client = GetClient(server);

            return(client.GetMultiple(keys, hashCodes, asString));
        }
Пример #46
0
        /// <summary>
        /// 替换更新数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void ReplaceFrom(string server, string key, object value)
        {
            MemcachedClient client = GetClient(server);

            client.Replace(key, value);
        }
Пример #47
0
        /// <summary>
        /// 从指定服务器获取
        /// </summary>
        /// <param name="server">服务器,Svr1,Svr2</param>
        /// <param name="key">键</param>
        /// <param name="value"></param>
        /// <param name="asString">是否把值作为字符串返回</param>
        public static object GetFrom(string server, string key, object value, bool asString)
        {
            MemcachedClient client = GetClient(server);

            return(client.Get(key, value, asString));
        }
Пример #48
0
 private MemcachedClientService()
 {
     this._client = new MemcachedClient();
 }
Пример #49
0
        /// <summary>
        ///  减小一个数值元素的值,减小多少由参数offset决定。 如果元素的值不是数值,以0值对待。如果减小后的值小于0,则新的值被设置为0
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="inc">增长幅度</param>
        /// <param name="hashCode">哈希码</param>
        /// <returns></returns>
        public static long DecrementFrom(string server, string key, long inc, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            return(client.Decrement(key, inc, hashCode));
        }
Пример #50
0
        /// <summary>
        /// 批量读取数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="keys">键集合</param>
        public static Hashtable GetMultipleFrom(string server, string[] keys)
        {
            MemcachedClient client = GetClient(server);

            return(client.GetMultiple(keys));
        }
Пример #51
0
        /// <summary>
        ///  将一个数值元素增加。 如果元素的值不是数值类型,将其作为0处理
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="inc">增长幅度</param>
        /// <returns></returns>
        public static long IncrementTo(string server, string key, long inc)
        {
            MemcachedClient client = GetClient(server);

            return(client.Increment(key, inc));
        }
Пример #52
0
        /// <summary>
        ///  设置数据缓存
        /// </summary>
        /// <param name="server">服务器,格式为Svr1,Svr2,Svr3,对应配置文件host</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expiry">过期时间</param>
        public static void SetTo(string server, string key, object value, DateTime expiry)
        {
            MemcachedClient client = GetClient(server);

            client.Set(key, value, expiry);
        }
Пример #53
0
        /// <summary>
        ///  存储一个数值元素
        /// </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        /// <param name="counter"></param>
        /// <param name="hashCode">哈希码</param>
        /// <returns></returns>
        public static bool StoreCounterTo(string server, string key, long counter, int hashCode)
        {
            MemcachedClient client = GetClient(server);

            return(client.StoreCounter(key, counter, hashCode));
        }
Пример #54
0
 public MemcachedEntityTagStore(IMemcachedClientConfiguration configuration)
 {
     _memcachedClient = new MemcachedClient(configuration);
 }
 static MemcachedClientService()
 {
     MemcachedClientService._instance = new MemcachedClientService();
     MemcachedClientService._client   = new MemcachedClient("memcached");
 }
Пример #56
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sectionName">Configuration section name</param>
 public MemcachedEntityTagStore(string sectionName)
 {
     _memcachedClient = new MemcachedClient(sectionName);
 }
Пример #57
0
        ///  <summary>
        /// 删除指定条件缓存
        ///  </summary>
        /// <param name="server"></param>
        /// <param name="key">键</param>
        public static bool DeleteFrom(string server, string key)
        {
            MemcachedClient client = GetClient(server);

            return(client.Delete(key));
        }
Пример #58
0
 public MemcachedEntityTagStore()
 {
     _memcachedClient = new MemcachedClient();
 }
Пример #59
0
        /// <summary>
        /// 批量读取数据缓存
        /// </summary>
        /// <param name="server"></param>
        /// <param name="keys">键集合</param>
        /// <param name="hashCodes">哈希码集合</param>
        /// <param name="asString">所有值返回字符</param>
        public static object[] GetMultipleArrayFrom(string server, string[] keys, int[] hashCodes, bool asString)
        {
            MemcachedClient client = GetClient(server);

            return(client.GetMultipleArray(keys, hashCodes, asString));
        }
 /// <summary>
 /// LocalCacheStrategy的构造函数
 /// </summary>
 public MemcachedObjectCacheStrategy()
 {
     _config = GetMemcachedClientConfiguration();
     _cache  = new MemcachedClient(_config);
 }