1. 程式人生 > >.Net負載均衡使用StateServer進行Session共享

.Net負載均衡使用StateServer進行Session共享

session的四種模式,預設的是Inproc

在負載均衡的時候使用這種模式會造成session不共享的問題,所以需要修改為StateServer模式

webconfig中SessionState需要修改為如下程式碼,其中stateConnectionString配置的連線是儲存session的連線 可以是本機127.0.0.1。或者是其他的遠端伺服器,預設埠號是42424

<sessionState cookieless="false" timeout="120" mode="StateServer" stateConnectionString="tcpip=10.18.193.200:42424"/>

儲存session的伺服器需要做一下配置修改

1.開啟登錄檔,執行cmd/regedit,找到節點HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\aspnet_state\Parameters

  a.將AllowRemoteConnection值設定為1 允許遠端連線

  b.將Port值設定為a5b8(十六進位制),即十進位制42424(預設值)  

2.將計算機服務"ASP.NET State Service"啟動型別改為自動,同時啟動改服務。

3.分別在網站專案A和網站專案B的Global.asax.cs中加入下面程式碼

  public override void Init()
        {
            base.Init();
            foreach (string moduleName in this.Modules)
            {
                string appName = ConfigurationManager.AppSettings["SessionKey"];
                IHttpModule module = this.Modules[moduleName];
                SessionStateModule ssm = module as SessionStateModule;
                if (ssm != null)
                {
                    FieldInfo storeInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
                    SessionStateStoreProviderBase store = (SessionStateStoreProviderBase)storeInfo.GetValue(ssm);
                    if (store == null)//In IIS7 Integrated mode, module.Init() is called later
                    {
                        FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
                        HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);
                        FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic);
                        appNameInfo.SetValue(theRuntime, appName);
                    }
                    else
                    {
                        Type storeType = store.GetType();
                        if (storeType.Name.Equals("OutOfProcSessionStateStore"))
                        {
                            FieldInfo uribaseInfo = storeType.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);
                            uribaseInfo.SetValue(storeType, appName);
                        }
                    }
                }
            }
        }

這裡的SessionKey 是寫在配置檔案中的

<!--給Session共享用的SessionKey -->
    <add  key ="SessionKey" value="HrssSession" />

這樣就完成了負載均衡中的session共享問題了