Beispiel #1
0
 static void MemClientInit()
 {
     try
     {
         ////初始化缓存
         MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
         //IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry("ocs.m.cnhzalicm10pub001.ocs.aliyuncs.com").AddressList[0].ToString()); //xxxx替换为ocs控制台上的“内网地址”
         //IPEndPoint ipEndPoint = new IPEndPoint(newaddress, 11211);
         //// 配置文件 - ip
         //memConfig.Servers.Add(ipEndPoint);
         //memConfig.AddServer("localhost:11211");
         //// 配置文件 - 协议
         //memConfig.Protocol = MemcachedProtocol.Binary;
         //// 配置文件-权限,如果使用了免密码功能,则无需设置userName和password
         //memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
         //memConfig.Authentication.Parameters["zone"] = "";
         //memConfig.Authentication.Parameters["userName"] = "******";
         //memConfig.Authentication.Parameters["password"] = "******";
         ////下面请根据实例的最大连接数进行设置
         //memConfig.SocketPool.MinPoolSize = 5;
         //memConfig.SocketPool.MaxPoolSize = 200;
         //MemClient = new MemcachedClient(memConfig);
         MemClient = new MemcachedClient();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #2
0
        internal MemCachedClient()
        {
            LoggerFactory logFactory = new LoggerFactory();

            logFactory.AddConsole(LogLevel.Information, true);
            m_Logger = logFactory.CreateLogger <MemCachedClient>();

            initializeParameters();

            using (m_Logger.BeginScope("Creating client '{0}:{1}'", HostName, Port))
            {
                try
                {
                    MemcachedClientConfiguration baseConfig    = null;
                    MemcachedClientOptions       configOptions = new MemcachedClientOptions();
                    configOptions.AddServer(HostName, Port);
                    configOptions.Protocol = Enyim.Caching.Memcached.MemcachedProtocol.Text;

                    baseConfig = new MemcachedClientConfiguration(new LoggerFactory(), configOptions);

                    m_Client = new MemcachedClient(new LoggerFactory(), baseConfig);

                    m_Logger.LogDebug("Memory cached client created.");
                }
                catch (Exception ex)
                {
                    m_Logger.LogError(ex, "Memory cache client creation failed.");
                }
            }
        }
        protected override IServiceCache CreateServiceCache()
        {
            var configuration = new MemcachedClientConfiguration();

            configuration.AddServer("degssql01", 11211);
            return(new MemcachedServiceCache(configuration));
        }
        public ActionResult Detalle(string IdOrden)
        {
            var currentUser = System.Web.HttpContext.Current.User as CustomPrincipal;

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

            //clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 32768));
            clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("192.168.99.100"), 32769));
            // se recupera la informacion de la orden en cache
            List <Orden> lstOrdenes;

            using (var ordencache = new MemcachedClient(clientConfiguration))
            {
                lstOrdenes = ((IEnumerable <Orden>)ordencache.Get("Orden-" + currentUser.UserName)).ToList();
            }

            // lstordenes =(List<OrdenModel>)HttpContext.Session["ListaOrden"] ;

            // se filtra el detalle de la orden
            var lstItems = lstOrdenes.Find(ord => ord.id_orden == IdOrden).item;

            ViewBag.IdOrden = IdOrden;


            return(View("_Detalle", lstItems.ToList()));
        }
Beispiel #5
0
        static void MemClientInit()
        {
            try
            {
                MemPrefix = (ConfigurationManager.AppSettings["MemCachedPrefix"] == null ? "" : ConfigurationManager.AppSettings["MemCachedPrefix"].ToString());
                string _sMemCachedIPPorts  = (ConfigurationManager.AppSettings["MemCachedIPPorts"] == null ? "" : ConfigurationManager.AppSettings["MemCachedIPPorts"].ToString());
                string _sMemCachedUserName = (ConfigurationManager.AppSettings["MemCachedUserName"] == null ? "" : ConfigurationManager.AppSettings["MemCachedUserName"].ToString());
                string _sMemCachedPassword = (ConfigurationManager.AppSettings["MemCachedPassword"] == null ? "" : ConfigurationManager.AppSettings["MemCachedPassword"].ToString());

                MemcachedClientConfiguration config = new MemcachedClientConfiguration();//创建配置参数
                string[] _arrMemCachedIPPorts       = _sMemCachedIPPorts.Split(';');
                for (int i = 0; i <= _arrMemCachedIPPorts.Length; i++)
                {
                    string _sMemCachedIP   = _arrMemCachedIPPorts[i].Split(',')[0];
                    int    _nMemCachedPort = int.Parse(_arrMemCachedIPPorts[i].Split(',')[1]);
                    config.Servers.Add(new IPEndPoint(IPAddress.Parse(_sMemCachedIP), _nMemCachedPort));//增加服务节点
                }
                config.Protocol            = MemcachedProtocol.Text;
                config.Authentication.Type = typeof(PlainTextAuthenticator);        //设置验证模式
                config.Authentication.Parameters["userName"] = _sMemCachedUserName; //用户名参数
                config.Authentication.Parameters["password"] = _sMemCachedPassword; //密码参数
                MemClient = new MemcachedClient(config);                            //创建客户端
            }
            catch (Exception ex)
            {
                LogHelper.LOG("MemClient", MethodBase.GetCurrentMethod().Name, "", "", "", ex.Source.ToString(), ex.Message.ToString());
            }
        }
Beispiel #6
0
    protected void btnMemOperate(object sender, EventArgs e)
    {
        string myConn = ConfigurationManager.AppSettings["BeITMemcacheIP"].ToString();
        MemcachedClientConfiguration config = new MemcachedClientConfiguration();

        config.AddServer(myConn, 11211);
        config.Protocol = MemcachedProtocol.Binary;
        MemcachedClient client = new MemcachedClient(config);

        string keyval  = key3.Text.Trim();
        ulong  number  = ulong.Parse(num.Text.Trim());
        string selflag = Select1.Value;
        ulong  renum;

        if (selflag.Equals("+"))
        {
            renum = client.Increment(keyval, 10, number);
            Response.Write("<script>window.alert('" + renum + "');window.location.href='../Mem_RedisTest.aspx'</script>");
        }
        else if (selflag.Equals("-"))
        {
            renum = client.Decrement(keyval, 10, number);
            Response.Write("<script>window.alert('" + renum + "');window.location.href='../Mem_RedisTest.aspx'</script>");
        }
    }
Beispiel #7
0
        static void Main(string[] args)
        {
            //MemcachedClientConfiguration config = new MemcachedClientConfiguration();
            //config.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            //config.Protocol = MemcachedProtocol.Binary;
            //MemcachedClient client = new MemcachedClient(config);
            //var p = new Person {Id = 1, Name = "wwee"};
            //client.Store(StoreMode.Set, "p", p,DateTime.Now.AddSeconds(10));
            //Person p1 = client.Get<Person>("p");
            //Console.WriteLine(p1.Name);
            //Console.ReadKey();
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            config.Protocol = MemcachedProtocol.Binary;
            MemcachedClient client = new MemcachedClient(config);
            var             p      = new Person {
                Id = 3, Name = "yzk"
            };

            //保存到缓存中
            //HttpContext.Cache.Insert(cacheKey, model, null,
            //DateTime.Now.AddSeconds(1),TimeSpan.Zero);
            client.Store(StoreMode.Set, "p" + p.Id, p, DateTime.Now.AddSeconds(3));//还可以指定第四个参数指定数据的过期时间。
            Thread.Sleep(2000);

            Person p1 = client.Get <Person>("p3");//HttpContext.Cache[cacheKey]

            Console.WriteLine(p1.Name);
            Thread.Sleep(2000);
            p1 = client.Get <Person>("p3");
            Console.WriteLine(p1.Name);
            Console.ReadKey();
        }
Beispiel #8
0
        //存储对象的类型若是自定义类的,则其必须是可序列化的
        public static void Test2()
        {
            //注意若是想把自定义的类的对象保存在MemCached服务器中,则这个类必须是可以序列化的
            //看我们自己定义的Person类,注意是加了[Serializable]特性的,若是不加可序列化的特性,则是无法把Person类型的对象保存在MemCached中的
            Person p = new Person()
            {
                Id = 001, Name = "shanzm"
            };

            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();

            memConfig.AddServer("127.0.0.1:11211");

            using (MemcachedClient memClient = new MemcachedClient(memConfig))
            {
                memClient.Store(Enyim.Caching.Memcached.StoreMode.Set, "p", p);
                Person perosn = memClient.Get <Person>("p");

                if (null == perosn)
                {
                    Console.WriteLine("无perosn缓存");
                }
                else
                {
                    Console.WriteLine($"{ perosn.Name}的Id是 {perosn.Id}");
                }
            }
            Console.ReadKey();
        }
        public MemcachedPostDataTemporaryStore(ILogger logger)
        {
            _logger = logger;
            var configuration = ReadConfiguration();

            TimeSpan.TryParse(configuration["TemporaryRequestStoragePeriod"].Value, out _storagePeriod);
            var temporaryRequestStorageMemcachedNodeEndPoint   = configuration["TemporaryRequestStorageMemcachedNodeEndPoint"].Value;
            var temporaryRequestStorageMemcachedConfigEndPoint = configuration["TemporaryRequestStorageMemcachedConfigEndPoint"].Value;

            if (String.IsNullOrWhiteSpace(temporaryRequestStorageMemcachedNodeEndPoint) && String.IsNullOrWhiteSpace(temporaryRequestStorageMemcachedConfigEndPoint))
            {
                throw new ConfigurationErrorsException($"{nameof(MemcachedPostDataTemporaryStore)}: Either Memcached Node or ElastiCache Memcached Config endpoint must be provided.");
            }
            if (_storagePeriod <= TimeSpan.Zero)
            {
                throw new ConfigurationErrorsException($"{nameof(MemcachedPostDataTemporaryStore)}: Storage period must be positive. Provided value: {_storagePeriod}");
            }

            IMemcachedClientConfiguration memcachedConfig;

            if (!String.IsNullOrWhiteSpace(temporaryRequestStorageMemcachedConfigEndPoint))
            {
                var memcachedConfigEndPoint = ParseEndPoint(temporaryRequestStorageMemcachedConfigEndPoint, "config");
                memcachedConfig = new ElastiCacheClusterConfig(memcachedConfigEndPoint.Item1, memcachedConfigEndPoint.Item2);
            }
            else
            {
                memcachedConfig = new MemcachedClientConfiguration();
                var memcachedNodeEndPoint = ParseEndPoint(temporaryRequestStorageMemcachedNodeEndPoint, "node");
                ((MemcachedClientConfiguration)memcachedConfig).AddServer(memcachedNodeEndPoint.Item1, memcachedNodeEndPoint.Item2);
            }
            _memcachedClient = new MemcachedClient(memcachedConfig);
        }
        public ActionResult DeleteItem(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"));
            }


            //Configuracion del MEMCACHED client
            var clientConfiguration = new MemcachedClientConfiguration {
                Protocol = MemcachedProtocol.Binary
            };

            clientConfiguration.Servers.Add(new IPEndPoint(IPAddress.Parse("192.168.99.100"), 32768));

            using (var memcachedclient = new MemcachedClient(clientConfiguration))
            {
                //consulto el cache del usuario logueado
                var cart = memcachedclient.Get <Cart>("Cart-" + currentUser.UserName);
                if (cart == null)
                {
                    return(View("Cart"));
                }
                var remove = new Item();
                //Consulto el item en el carrito y le resto al cantidad si llega a cero lo elimino.
                foreach (var i in cart.Items.Where(i => i.Producto.id_producto == idProducto))
                {
                    if (i.Cantidad > cantidad)
                    {
                        i.Cantidad = i.Cantidad - cantidad;
                    }
                    else
                    {
                        remove = i;
                    }
                }
                if (!remove.Equals(null))
                {
                    cart.Items.Remove(remove);
                }
                if (cart.Items.Count != 0)
                {
                    memcachedclient.Store(StoreMode.Set, "Cart-" + currentUser.UserName, cart);
                }
                else
                {
                    memcachedclient.Remove("Cart-" + currentUser.UserName);
                }

                return(View("Cart", cart));
            }
        }
        /// <summary>
        /// Gets the database connection.
        /// </summary>
        public virtual MemcachedClient GetClient()
        {
            if (!_options.IsUseConfigSetting)
            {
                //初始化缓存
                string host    = _options.ConnectionString;
                var    options = new MemcachedClientOptions();
                MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration(_loggerFacotry, options);
                //   IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry(host).AddressList[0].ToString());//your_ocs_host替换为OCS内网地址
                //   IPEndPoint ipEndPoint = new IPEndPoint(newaddress, 11211);
                DnsEndPoint dnsEndPoint = new DnsEndPoint(host, 11211);

                // 配置文件 - ip
                memConfig.Servers.Add(dnsEndPoint);
                // 配置文件 - 协议
                memConfig.Protocol = MemcachedProtocol.Binary;
                // 配置文件-权限
                memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
                memConfig.Authentication.Parameters["zone"]     = "";
                memConfig.Authentication.Parameters["userName"] = _options.CacheServerUid;
                memConfig.Authentication.Parameters["password"] = _options.CacheServerPwd;
                //下面请根据实例的最大连接数进行设置
                memConfig.SocketPool.MinPoolSize = 5;
                memConfig.SocketPool.MaxPoolSize = 200;
                return(new MemcachedClient(_loggerFacotry, memConfig));
            }
            else
            {
                var options = new MemcachedClientOptions();
                UtilConf.Configuration.GetSection("enyimMemcached").Bind(options);
                return(new MemcachedClient(_loggerFacotry, new MemcachedClientConfiguration(_loggerFacotry, options)));
            }
        }
Beispiel #12
0
    protected void btnMemPend(object sender,EventArgs e)
    {
        string myConn = ConfigurationManager.AppSettings["BeITMemcacheIP"].ToString();
        MemcachedClientConfiguration config = new MemcachedClientConfiguration();
        config.AddServer(myConn, 11211);
        config.Protocol = MemcachedProtocol.Binary;
        MemcachedClient client = new MemcachedClient(config);
        string pkey=pendkey.Text.Trim();
        string select = Sele.Value;
        //string pdata=penddata.Text.Trim();
        byte[] b={49,50,51};
        ArraySegment<byte> pend=new ArraySegment<byte>(b);

        if (select.Equals("Prepend"))
        {
            if (client.Prepend(pkey, pend))
                Response.Write("<script>window.alert('向前追加数据成功!');window.location.href='../Mem_RedisTest.aspx'</script>");
            else
                Response.Write("<script>window.alert('向前追加数据失败!');window.location.href='../Mem_RedisTest.aspx'</script>");
        }
        else if(select.Equals("Append"))
        {
            if (client.Append(pkey, pend))
                Response.Write("<script>window.alert('追加数据成功!');window.location.href='../Mem_RedisTest.aspx'</script>");
            else
                Response.Write("<script>window.alert('追加数据失败!');window.location.href='../Mem_RedisTest.aspx'</script>");
        }

    }
Beispiel #13
0
        static void Main(string[] args)
        {
            MemcachedClientConfiguration mcConfig = new MemcachedClientConfiguration();

            mcConfig.AddServer("127.0.0.1:11211");//必须指定端口
            using (MemcachedClient client = new MemcachedClient(mcConfig))
            {
                //client.Store(Enyim.Caching.Memcached.StoreMode.Set, "name", "yzk");
                //string name=(string) client.Get("name");

                //client.Store(Enyim.Caching.Memcached.StoreMode.Set, "p1", new Person { Name="dalong",Age=18});

                //Person person=(Person) client.Get("p1");

                //Console.WriteLine(person.Name+","+person.Age);

                var cas = client.GetWithCas("name");
                Console.WriteLine("按任意键继续");
                Console.ReadKey();
                var res = client.Cas(Enyim.Caching.Memcached.StoreMode.Set, "name", cas.Result + "1",
                                     cas.Cas);
                if (res.Result)
                {
                    Console.WriteLine("修改成功" + cas.Result);
                }
                else
                {
                    Console.WriteLine("被别人改了" + cas.Result);
                }
            }

            Console.ReadKey();
        }
Beispiel #14
0
        private MemcachedMg()
        {
            //获取配置信息
            var settingService =
                DependencyResolver.Current.GetService <ISettingService>();

            string[] servers
                = settingService.GetValue("MemCachedServers").Split(';');


            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            //Memcached的配置
            foreach (var server in servers)//获取所有的服务器地址并添加到Memcached
            {
                config.Servers.Add(new IPEndPoint(IPAddress.Parse(server), 11211));
            }
            //config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
            //config.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            //要连接到哪台服务器,可以连接到多台服务器
            //11211  是Memcached默认端口

            config.Protocol = MemcachedProtocol.Binary;
            //Binary 通过什么方式(Binary)序列化这个类,要求这个类必须标记为可序列化
            //默认是Binary,text是用json保存


            client = new MemcachedClient(config);
        }
        public void TestFixtureSetup()
        {
            _cacheService = new MemcachedService(new TimeSpan(0, 10, 0));

            ProcessStartInfo memcacheInfo;

            memcacheInfo = new ProcessStartInfo(MemcacheProcessHelper.MemcachePath);
            memcacheInfo.WorkingDirectory       = Path.GetDirectoryName(MemcacheProcessHelper.MemcachePath);
            memcacheInfo.Arguments              = string.Format("-p {0} -vvv", port);
            memcacheInfo.UseShellExecute        = true;
            memcacheInfo.CreateNoWindow         = false;
            memcacheInfo.RedirectStandardError  = false;
            memcacheInfo.RedirectStandardOutput = false;
            memcacheProcess = Process.Start(memcacheInfo);

            //Spin until memcached can accept requests
            while (!memcacheProcess.Responding)
            {
            }

            var config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Loopback, port));
            config.Protocol = MemcachedProtocol.Binary;

            MemcachedService.Initialize(config);
        }
Beispiel #16
0
        //Cas操作
        //Cas 类似数据库的乐观锁,但是我们使用Memcached一般只是用来缓存数据,一般是不需要使用Cas的
        public static void TestCas()
        {
            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();

            memConfig.AddServer("127.0.0.1:11211");
            using (MemcachedClient memClient = new MemcachedClient(memConfig))
            {
                memClient.Store(Enyim.Caching.Memcached.StoreMode.Set, "Name", "shanzm");

                CasResult <string> nameWithCas = memClient.GetWithCas <string>("Name");
                Console.WriteLine($"读取的数据Name={nameWithCas.Result },Cas:{nameWithCas.Cas }"); //第一个运行的程序此时的Cas=1

                Console.WriteLine("你此时在源文件中点击运行,“003Cas操作.exe”,抢先运行,点击回车进行下面的修改");            //另外的程序读取Name的Cas=2
                Console.ReadKey();

                CasResult <bool> updateWithCas = memClient.Cas(StoreMode.Set, "Name", "shanzm修改版本", nameWithCas.Cas);

                if (updateWithCas.Result)
                {
                    Console.WriteLine("Name修改成功,现在的Cas:" + updateWithCas.Cas);//另外的程序此处的Cas为3
                }
                else
                {
                    Console.WriteLine("更新失败,被其他程序抢先了,现在的Cas:" + updateWithCas.Cas);//第一个运行的程序的Cas此时为0
                }
                Console.ReadKey();
            }
        }
Beispiel #17
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");
		}
        private static IMemcachedClientConfiguration GetConfig()
        {
            //MemcachedClientConfiguration config = new MemcachedClientConfiguration();
            ////config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
            //config.AddServer("127.0.0.1", 11211);
            //config.Protocol = MemcachedProtocol.Text;
            ////config.Authentication.Type = typeof(PlainTextAuthenticator);
            ////config.Authentication.Parameters["userName"] = "******";
            ////config.Authentication.Parameters["password"] = "******";

            //var mc = new MemcachedClient(config);
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            //http://stackoverflow.com/questions/4470758/enyim-memcached-client-does-not-write-read-data
            //also need to add	else cmd_get and cmd_set stats counters remain constant. The call to client.Get returns null.
            //config.Protocol = MemcachedProtocol.Text; to make the

            //config.AddServer("127.0.0.1", 11211);
            config.AddServer(ConfigHelper.MemcacheHost1, ConfigHelper.MemcachePort1);
            //mc.AddServer(ConfigHelper.MemcacheHost2,ConfigHelper.MemcachePort2);
            config.Protocol = MemcachedProtocol.Text;
            //config.SocketPool.MinPoolSize = 10;
            //config.SocketPool.MaxPoolSize = 50;


            return(config);
        }
Beispiel #19
0
        public async Task OpenAsync(string correlationId)
        {
            var connections = await _connectionResolver.ResolveAllAsync(correlationId);

            if (connections.Count == 0)
            {
                throw new ConfigException(correlationId, "NO_CONNECTION", "Connection is not configured");
            }

            var options = new MemcachedClientConfiguration();

            foreach (var connection in connections)
            {
                var uri = connection.Uri;

                if (!string.IsNullOrEmpty(uri))
                {
                    options.AddServer(uri, 11211);
                }
                else
                {
                    var host = connection.Host ?? "localhost";
                    var port = connection.Port != 0 ? connection.Port : 11211;

                    options.AddServer(host, port);
                }
            }

            _client = new MemcachedClient(null, options);
        }
        public static MemcachedClientConfiguration MemClientInit()
        {
            //初始化缓存
            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
            IPAddress  newaddress = IPAddress.Parse(Dns.GetHostEntry(Ip).AddressList[0].ToString()); //xxxx替换为ocs控制台上的“内网地址”
            IPEndPoint ipEndPoint = new IPEndPoint(newaddress, int.Parse(Port));

            //配置文件 - ip
            memConfig.Servers.Add(ipEndPoint);
            //   配置文件 - 协议
            memConfig.Protocol = Protocol;
            // 配置文件 - 权限,如果使用了免密码功能,则无需设置userName和password

            if (OpenAuth)
            {
                memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
                memConfig.Authentication.Parameters["userName"] = AuthPara["userName"];
                memConfig.Authentication.Parameters["password"] = AuthPara["password"];
                memConfig.Authentication.Parameters["zone"]     = AuthPara["zone"];
            }

            // memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
            //memConfig.Authentication.Parameters["zone"] = "";
            //memConfig.Authentication.Parameters["userName"] = "******";
            //memConfig.Authentication.Parameters["password"] = "******";

            //下面请根据实例的最大连接数进行设置
            //memConfig.SocketPool.MinPoolSize = 5;
            // memConfig.SocketPool.MaxPoolSize = 200;
            //   MemClient = new MemcachedClient(memConfig);

            return(memConfig);
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            //Install-Package EnyimMemcached
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            //Parse(服务的ip地址),代表连接哪台服务器
            config.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            //用Binary,类必须标注[Serializable]可序列化
            config.Protocol = MemcachedProtocol.Binary;
            //为了利用连接池不要using MemcachedClient ,而是使用一个static对象
            MemcachedClient client = new MemcachedClient(config);
            //创建一个对象
            var p = new Person {
                Id = 3, Name = "yzk"
            };

            //保存到缓存中
            //HttpContext.Cache.Insert(cacheKey, model, null,
            //DateTime.Now.AddSeconds(1),TimeSpan.Zero);
            // "p" + p.Id这个缓存的key,p是缓存的值
            client.Store(StoreMode.Set, "p" + p.Id, p, DateTime.Now.AddSeconds(3));//还可以指定第四个参数指定数据的过期时间。
            Thread.Sleep(2000);

            //从memcache中取出来
            Person p1 = client.Get <Person>("p3");//等价于HttpContext.Cache[cacheKey]

            Console.WriteLine(p1.Name);
            Thread.Sleep(2000);
            p1 = client.Get <Person>("p3");
            Console.WriteLine(p1.Name);
            Console.ReadKey();
        }
Beispiel #22
0
        private MemcacheMgr()
        {
            var Configuration = new MemcachedClientConfiguration();

            Configuration.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            Configuration.Protocol = MemcachedProtocol.Binary;
            Client = new MemcachedClient(Configuration);
        }
Beispiel #23
0
        private MemcachedMgr()
        {
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11211));
            config.Protocol = MemcachedProtocol.Binary;
            client          = new MemcachedClient(config);
        }
Beispiel #24
0
        public void Setup()
        {
            var configuration = new MemcachedClientConfiguration();

            configuration.AddServer("127.0.0.1", PortNumber);
            _memcachedEntityTagStore = new MemcachedEntityTagStore(configuration);
            _memcachedEntityTagStore.Clear();
        }
Beispiel #25
0
        public MemcachedClient GetClient(string hostname, int port)
        {
            var config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(Dns.GetHostEntry(hostname).AddressList[0], port));
            config.SocketPool.ReceiveTimeout = new TimeSpan(0, 0, 15);
            return(new MemcachedClient(config));
        }
        /// <summary>
        /// LocalCacheStrategy的构造函数
        /// </summary>
        MemcachedObjectCacheStrategy(/*ILoggerFactory loggerFactory, IOptions<MemcachedClientOptions> optionsAccessor*/)
        {
            _config = GetMemcachedClientConfiguration();
            var            provider      = OFoodDI.GetIServiceProvider();
            ILoggerFactory loggerFactory = provider.GetService <ILoggerFactory>();

            Cache = new MemcachedClient(loggerFactory, _config);
        }
        public void SetUp()
        {
            var config = new MemcachedClientConfiguration();

            config.AddServer("127.0.0.1", 11211);

            _Client = new MemcachedClient(config);
        }
        public static void ConfigTest()
        {
            MemcachedClientConfiguration mc = new MemcachedClientConfiguration();

            mc.Protocol = MemcachedProtocol.Text;
            mc.AddServer(ConfigHelper.MemcacheHost1, ConfigHelper.MemcachePort1);
            //mc.AddServer(ConfigHelper.MemcacheHost2,ConfigHelper.MemcachePort2);
        }
Beispiel #29
0
        public CachedAccess()
        {
            var ipServer = ConfigurationManager.AppSettings["CachedIp"] ?? "127.0.0.1";
            var config   = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Parse(ipServer), 11211));
            _cached = new MemcachedClient(config);
        }
Beispiel #30
0
        private MemcacheMgr()
        {
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();

            config.Servers.Add(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211));
            config.Protocol = MemcachedProtocol.Binary;
            client          = new MemcachedClient(config);
        }