1. 安装
将 memcached for Windows 压缩包解压后执行下面命令安装服务: c:memcached> memcached -d 服务名称是 "memcached Server"我们可以使用 "memcached -d un" 删除服务 CMD命令行操作: memcached -d start # 启动服务 memcached -d stop # 停止服务 memcached -d restart # 这个命令好像有问题~~~ memcached -h # 显示帮助信息 有些命令需要通过服务参数来执行我们可以用下面思路方法修改这些服务参数修改前先停止 memcached 服务 (1) 打开注册表找到 HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesmemcached Server (2) 修改 ImagePath 项比如 ""C:memcachedmemcached.exe" -d runservice -m 100 -p 1234"这样服 务启动后监听端口就成了 1234最大缓存Cache内存就是 100 MB 2. 客户端编程 首先到 .NET memcached client library 下载客户端类库 我们首先要做是化网络连接参数var pool = SockIOPool.GetInstance; pool.SetServers( { "192.168.1.101:1234", "192.168.1.102:1234" }); pool.InitConnections = 3; pool.MinConnections = 3; pool.MaxConnections = 5; pool.SocketConnectTimeout = 1000; pool.SocketTimeout = 3000; pool.MaenanceSleep = 30; pool.Failover = true; pool.Nagle = false; pool.Initialize; 通常情况下我们只需使用默认 SockIOPool当然也可以用 SockIOPool.GetInstance( poolName) 化多个 环境以提供区别服务器组或者连接参数 var pool = SockIOPool.GetInstance("cache2"); pool.SetServers( { "192.168.1.101:1235" }); pool.InitConnections = 3; pool.MinConnections = 3; pool.MaxConnections = 5; pool.SocketConnectTimeout = 1000; pool.SocketTimeout = 3000; pool.MaenanceSleep = 30; pool.Failover = true; pool.Nagle = false; pool.Initialize; // ------------------ var client = MemcachedClient { EnableCompression = true }; client.PoolName = "cache2"; client.Set("a", 100); 化只需在第次缓存Cache操作的前即可接下来我们可以创建 MemcachedClient 对象连接 memcached Server 进行相关操作以下是代码演示 var client = MemcachedClient; // a. 设置 client.Set("a", 100); // b. 获取 client.Get("a"); // c. 判断 var b = client.KeyExists("a"); // d. 删除 client.Delete("a"); // e. 添加 (服务器上必须没有相同 Key 存在) (client.KeyExists("a")) client.Delete("a"); client.Add("a", 123); // f. 替换 (服务器上必须有相同 Key 存在) (!client.KeyExists("a")) client.Set("a", 1); client.Replace("a", 4567); // g. 计数器 client.StoreCounter("i", 100); for ( i = 0; i < 3; i) { client.Increment("i", 1); // 递增 var count = client.GetCounter("i"); Console.WriteLine(count); } for ( i = 0; i < 5; i) { client.Decrement("i", 1); // 递减 var count = client.GetCounter("i"); Console.WriteLine(count); } // h. 清除服务器上所有数据 client.FlushAll; // i. 次获取多个数据减少网络传输时间 client.Set("a", 1); client.Set("b", 2); client.Set("c", 3); var vs = client.GetMultiple( { "a", "b", "c" }); foreach (var item in vs.Keys) { Console.WriteLine("{0}={1}", item, vs[item]); } var ar = client.GetMultipleArray( { "a", "b", "c" }); // 仅返回 value foreach (var item in ar) { Console.WriteLine(item); } // j. 获取服务器信息 var stats = client.Stats; foreach (var server in stats.Keys) { Console.WriteLine(server); Console.WriteLine("-------------"); var infos = stats[server] as Hashtable; foreach (var item in infos.Keys) { Console.WriteLine("{0}={1}", item, infos[item]); } } 2009-1-15 22:45:53 疯狂代码 http://www./ |
|
来自: thy > 《Memcached》