Memcache分布式实战
Ps:经过半天的努力,终于初窥memcache门径,记录分享。
三部曲<大纲>
1、安装服务
2、WebConfig配置
3、程序中引用相应dll
4、编码
5、telnet中监测
1、安装参考 http://www.2cto.com/os/201205/132641.html
1)安装比较简单无难度,参考上面博文的步骤,应该没有问题。
2、WebConfig中配置是关键,参考如下代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0"?> 2 3 <!-- 4 For more information on how to configure your ASP.NET application, please visit 5 http://go.microsoft.com/fwlink/?LinkId=169433 6 --> 7 8 <configuration> 9 10 <configSections> 11 <!--在web.config里找到configSections节点,添加以下内容--> 12 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 13 <section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" allowDefinition="MachineToApplication" restartOnExternalChanges="true"/> 14 <sectionGroup name="enyim.com"> 15 <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching"/> 16 </sectionGroup> 17 </configSections> 18 <enyim.com> 19 <memcached> 20 <servers> 21 <!-- put your own server(s) here--> 22 <add address="192.168.1.216" port="11211"/> 23 </servers> 24 <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00"/> 25 </memcached> 26 </enyim.com> 27 <cacheProvider defaultProvider="MemcachedCacheProvider"> 28 <providers> 29 <add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders" keySuffix="_MySuffix_" defaultExpireTime="2000"/> 30 </providers> 31 </cacheProvider> 32 <!--在configSections节点之外,增加以下内容:--> 33 <log4net> 34 <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> 35 <param name="File" value="LogFiles/"/> 36 <param name="AppendToFile" value="true"/> 37 <param name="MaxSizeRollBackups" value="10"/> 38 <param name="StaticLogFileName" value="false"/> 39 <param name="DatePattern" value="yyyyMMdd/'log.log'"/> 40 <param name="RollingStyle" value="Date"/> 41 <layout type="log4net.Layout.PatternLayout"> 42 <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline"/> 43 </layout> 44 </appender> 45 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> 46 <layout type="log4net.Layout.PatternLayout"> 47 <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline" /> 48 </layout> 49 </appender> 50 <root> 51 <level value="ALL" /> 52 <appender-ref ref="RollingLogFileAppender" /> 53 <appender-ref ref="ConsoleAppender" /> 54 </root> 55 <logger name="Memcached.ClientLibrary"> 56 <level value="WARN" /> 57 58 </logger> 59 </log4net> 60 <connectionStrings> 61 <add name="ApplicationServices" 62 connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" 63 providerName="System.Data.SqlClient" /> 64 </connectionStrings> 65 66 <system.web> 67 <compilation debug="true" targetFramework="4.0" /> 68 69 <authentication mode="Forms"> 70 <forms loginUrl="~/Account/Login.aspx" timeout="2880" /> 71 </authentication> 72 73 <membership> 74 <providers> 75 <clear/> 76 <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" 77 enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" 78 maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" 79 applicationName="/" /> 80 </providers> 81 </membership> 82 83 <profile> 84 <providers> 85 <clear/> 86 <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> 87 </providers> 88 </profile> 89 90 <roleManager enabled="false"> 91 <providers> 92 <clear/> 93 <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> 94 <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> 95 </providers> 96 </roleManager> 97 98 </system.web> 99 100 <system.webServer> 101 <modules runAllManagedModulesForAllRequests="true"/> 102 </system.webServer> 103 </configuration>
3、引用dll
4、编码
1)application start中添加如下代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 void Application_Start(object sender, EventArgs e) 2 { 3 // Code that runs on application startup 4 try 5 { 6 string[] serverlist = new string[] { "192.168.1.216:11211" }; ; 7 8 string poolName = "MemcacheIOPool"; 9 // initialize the pool for memcache servers 10 11 SockIOPool pool = SockIOPool.GetInstance(poolName); 12 13 //设置连接池的初始容量,最小容量,最大容量,Socket 读取超时时间,Socket连接超时时间 14 15 pool.SetServers(serverlist); 16 17 pool.InitConnections = 1; 18 19 pool.MinConnections = 1; 20 21 pool.MaxConnections = 500; 22 23 pool.SocketConnectTimeout = 1000; 24 25 pool.SocketTimeout = 3000; 26 27 pool.MaintenanceSleep = 30;//表示是否需要延时结束 28 29 pool.Failover = true;//表示对于服务器出现问题时的自动修复。 30 31 pool.Nagle = false; 32 33 pool.Initialize();//容器初始化 34 } 35 catch (Exception err) 36 { 37 log4net.ILog log = log4net.LogManager.GetLogger("log"); 38 log.Info(err); 39 } 40 }
2) set cookie
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public partial class _Default : System.Web.UI.Page
2 {
3 string poolName = "MemcacheIOPool";
4 // [STAThread]
5 protected void Page_Load(object sender, EventArgs e)
6 {
7 MemcachedClient mc = new MemcachedClient();//实例化一个客户端
8
9 mc.PoolName = poolName;
10
11 mc.EnableCompression = false;
12
13 string key = "user_info";//key值
14
15 object obj = new object();
16
17 if (!mc.KeyExists(key)) //测试缓存中是否存在key的值
18 {
19 mc.Add("list", CreateListInt(), System.DateTime.Now.AddMinutes(30));
20 mc.Set("dd", "cc", System.DateTime.Now.AddMinutes(30));
21 mc.Set("dic", CreateDic(), System.DateTime.Now.AddMinutes(30));
22 }
23 }
24
25 protected List<int> CreateListInt()
26 {
27 int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 11 };
28 List<int> list = new List<int>();
29 foreach (int item in intArray)
30 {
31 list.Add(item);
32 }
33 return list;
34 }
35
36 protected Dictionary<int, string> CreateDic()
37 {
38 Dictionary<int, string> dic = new Dictionary<int, string>();
39 dic.Add(1, "hacksl");
40 dic.Add(2, "magusW");
41 dic.Add(3, "jack");
42 dic.Add(4, "helen");
43 return dic;
44 }
5、TelNet中监测
开启telnet服务 http://jingyan.baidu.com/article/8065f87fc3b31123312498e5.html
1) cmd 中 输入 telnet 192.168.1.xx 11211
2) http://www.cnblogs.com/jeffwongishandsome/archive/2011/11/06/2238265.html 可参考这里面的命令
完工。
如有遗漏请留言。测试源码会稍后上传。