Memcached Tip 2:Session同步
http://memcachedproviders.codeplex.com/提供的Memcached客户端支持Asp.net站点中的Session同步,其原理是接管Asp.net的Session处理,同时在后台使用数据库支持完成WEB集群的Session的同步。具体实现步骤如下:
1:数据库准备
下载完毕Memcached providers之后,在解压目录下有:
一个用于创建数据库表,一个用于创建这个provider的需要用到的存储过程。
2:配置sessionState
sessionState的配置如下,为了完整性期间,这里给出Web.config的全部配置部分,包括分布式缓存的Memcached的配置:
<?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="cacheProvider" type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders" allowDefinition="MachineToApplication" restartOnExternalChanges="true"/> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" /> </sectionGroup> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net> <!-- Define some output appenders --> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <!--<threshold value="OFF" />--> <!-- Setup the root category, add the appenders and set the default priority --> <root> <priority value="WARN"/> <appender-ref ref="ConsoleAppender"> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="WARN"/> <levelMax value="FATAL"/> </filter> </appender-ref> </root> </log4net> <enyim.com> <memcached> <servers> <!-- put your own server(s) here--> <add address="192.168.0.96" port="11211" /> <!--<add address="192.168.0.101" port="11211" />--> </servers> <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" /> </memcached> </enyim.com> <cacheProvider defaultProvider="MemcachedCacheProvider"> <providers> <add name="MemcachedCacheProvider" type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders" keySuffix="_MySuffix_" defaultExpireTime="2000"/> </providers> </cacheProvider> <connectionStrings> <add name="ApplicationServices" connectionString="Data Source=192.168.0.96;Initial Catalog=ForestFire;User Id=sa;Password=sa;" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <sessionState cookieless="false" regenerateExpiredSessionId="true" mode="Custom" customProvider="MemcachedSessionProvider"> <providers> <add name="MemcachedSessionProvider" type="MemcachedProviders.Session.SessionStateProvider,MemcachedProviders" connectionStringName="ApplicationServices" dbType="SQL" writeExceptionsToEventLog="false" /> </providers> </sessionState> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="2880" /> </authentication> <membership> <providers> <clear/> <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership> <profile> <providers> <clear/> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/> </providers> </profile> <roleManager enabled="false"> <providers> <clear/> <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" /> <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" /> </providers> </roleManager> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> </configuration>
3:代码
代码没有任何稀奇的,和传统的Session操作一样,如下:
protected void Page_Load(object sender, EventArgs e) { try { Session["name"] = "豆腐"; } catch (Exception err) { Response.Write(err.Message); } } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = Session["name"].ToString(); }
全部代码下载如下:WebApplication20110817.rar