Memcache 学习记录

Memcache简介:

Memcached是由Danga Interactive开发的,高性能的,分布式的内存对象缓存系统,用于在动态应用中减少数据库负载,提升访问速度。

Memcache使用

第一步:安装Memcache服务端

  32位链接:https://pan.baidu.com/s/1bpEYRDX 密码:jyu6

   64位链接:https://pan.baidu.com/s/1nuVtktb 密码:pqiw

   1 解压缩文件到c:\memcached(随便哪个盘都行)
   2 命令行输入 'c:\memcached\memcached.exe -d install' 
   3 命令行输入 'c:\memcached\memcached.exe -d start' ,该命令启动 Memcached ,默认监听端口为 11211

到此就可以在系统服务中找到Memcache服务了

 

第二步:下载所需库文件

链接:https://pan.baidu.com/s/1i4Dk3qP 密码:gch7

Commons.dll

ICSharpCode.SharpZipLib.dll

log4net.dll

Memcached.ClientLibrary.dll

第三步:封装设置和获取

 1 using Memcached.ClientLibrary;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Web;
 6 
 7 
 8 public class MemcacheHelper
 9 {
10     private static readonly MemcachedClient mc = null;
11     static MemcacheHelper()
12     {
13         string[] serverlist = { "127.0.0.1:11211", "10.0.0.132:11211" };
14 
15         //初始化池
16         SockIOPool pool = SockIOPool.GetInstance();
17         pool.SetServers(serverlist);
18 
19         pool.InitConnections = 3;
20         pool.MinConnections = 3;
21         pool.MaxConnections = 5;
22 
23         pool.SocketConnectTimeout = 1000;
24         pool.SocketTimeout = 3000;
25 
26         pool.MaintenanceSleep = 30;
27         pool.Failover = true;
28 
29         pool.Nagle = false;
30         pool.Initialize();
31 
32         // 获得客户端实例
33         mc = new MemcachedClient();
34         mc.EnableCompression = false;
35 
36     }
37     /// <summary>
38     /// 向Memcache存储数据
39     /// </summary>
40     /// <param name="key"></param>
41     /// <param name="value"></param>
42     public static void Set(string key, object value)
43     {
44         mc.Set(key, value);
45     }
46     /// <summary>
47     /// 向Memcache存储数据
48     /// </summary>
49     /// <param name="key"></param>
50     /// <param name="value"></param>
51     /// <param name="time"></param>
52     public static void Set(string key, object value, DateTime time)
53     {
54         mc.Set(key, value, time);
55     }
56     /// <summary>
57     /// 获取Memcache中的数据
58     /// </summary>
59     /// <param name="key"></param>
60     /// <returns></returns>
61     public static object Get(string key)
62     {
63         if (mc.KeyExists(key))
64         {
65             return mc.Get(key);
66         }
67         return null;
68     }
69     /// <summary>
70     /// 删除
71     /// </summary>
72     /// <param name="key"></param>
73     /// <returns></returns>
74     public static bool Delete(string key)
75     {
76         if (mc.KeyExists(key))
77         {
78             return mc.Delete(key);
79         }
80         return false;
81     }
82 }

serverlist中存储的是缓存服务器的IP地址和端口号,在实际项目中缓存服务器的IP地址和端口号一遍都存在配置文件中一遍修改和添加

 

posted on 2017-12-18 17:03  有梦想的咸鱼¥  阅读(117)  评论(0编辑  收藏  举报

导航