现在我们来看看Session Management真正的实现,和我以前的例子不同,我不是把所有的实现都写在WCF service上,而是定义了另一个class来实现所有的业务逻辑:SessionManager。我们分析一下具体的实现逻辑。

namespace Artech.SessionManagement.Service
   2: {
class SessionManager
   4:     {
object(); 
   6:  
static TimeSpan Timeout
   8:         { get; set; } 
   9:  
static IDictionary<Guid, SessionInfo> CurrentSessionList
  11:         { get; set; } 
  12:  
static IDictionary<Guid, ISessionCallback> CurrentCallbackList
  14:         { get; set; } 
  15:  
static SessionManager()
  17:         {
];
string.IsNullOrEmpty(sessionTimeout))
  20:             {
);
  22:             } 
  23:  
double timeoutMinute;
out timeoutMinute))
  26:             {
);
  28:             }           
  29:  
int)(timeoutMinute * 60));
new Dictionary<Guid, SessionInfo>();
new Dictionary<Guid, ISessionCallback>();
  33:         }
//...
  35:   }
  36: }
  37:  

首先来看Field、Property和static constructor的定义。_syncHelper 用于实现多线程同步之用;Timeout是session timeout的时间,可配置;CurrentSessionList和CurrentCallbackList两个dictionary在上面我们已经作过介绍,分别代表当前活动的session列表和callback列表,key均为SessionID。在静态构造函数中,初始化session timeout的时间,和实例化CurrentSessionList和CurrentCallbackList。

接着我们来看看StartSession和EndSession两个方法,这两个方法分别代表Session的开始和结束。

static Guid StartSession(SessionClientInfo clientInfo)
   2: {
   3:     Guid sessionID = Guid.NewGuid();
   4:     ISessionCallback callback = OperationContext.Current.GetCallbackChannel<ISessionCallback>();
new SessionInfo() { SessionID = sessionID, StartTime = DateTime.Now,  LastActivityTime = DateTime.Now, ClientInfo = clientInfo };
lock (_syncHelper)
   7:     {
   8:         CurrentSessionList.Add(sessionID, sesionInfo);
   9:         CurrentCallbackList.Add(sessionID, callback);
  10:     }
return sessionID;
  12: } 
  13:  
void EndSession(Guid sessionID)
  15: {
if (!CurrentSessionList.ContainsKey(sessionID))
  17:     {
return;
  19:     } 
  20:  
lock (_syncHelper)
  22:     {
  23:         CurrentCallbackList.Remove(sessionID);
  24:         CurrentSessionList.Remove(sessionID);
  25:     }
  26: } 

在StartSession方法中,首先创建一个GUID作为SessionID。通过OperationContext.Current获得callback对象,并根据client端传入的SessionClientInfo 对象创建SessionInfo 对象,最后将callback对象和SessionInfo 对象加入CurrentCallbackList和CurrentSessionList中。由于这两个集合会在多线程的环境下频繁地被访问,所以在对该集合进行添加和删除操作时保持线程同是显得尤为重要,所在在本例中,所有对列表进行添加和删除操作都需要获得_syncHelper加锁下才能执行。与StartSession相对地,EndSession方法仅仅是将SessionID标识的callback对象和SessionInfo 对象从列表中移除。

然后我们来看看如何强行中止掉一个或多个活动的session:KillSessions。

void KillSessions(IList<Guid> sessionIDs)
   2: {
lock (_syncHelper)
   4:     {
in sessionIDs)
   6:         {
if (!CurrentSessionList.ContainsKey(sessionID))
   8:             {
continue;
  10:             } 
  11:  
  12:             SessionInfo sessionInfo = CurrentSessionList[sessionID];
  13:             CurrentSessionList.Remove(sessionID);
  14:             CurrentCallbackList[sessionID].OnSessionKilled(sessionInfo);
  15:             CurrentCallbackList.Remove(sessionID);
  16:         }
  17:     }
  18: } 

逻辑很简单,就是先从CurrentSessionList中获得对应的SessionInfo 对象,然后将其从CurrentSessionList中移除,然后根据SessionID获得对用的Callback对象,调用OnSessionKilled方法实时通知client session被强行中止,最后将callback对象从CurrentCallbackList中清楚。需要注意的是OnSessionKilled是One-way方式调用的,所以是异步的,时间的消耗可以忽略不计,也不会抛出异常,所以对_syncHelper的锁会很开释放,所以不会对并发造成太大的影响。

Session的管理最终要、也是作复杂的事对Timeout的实现,再我们的例子中,我们通过定期对CurrentSessionList中的每个session进行轮询实现。每次轮询通过RenewSessions方法实现,我们来看看该方法的定义:

   1: [MethodImpl(MethodImplOptions.Synchronized)]
void RenewSessions()
   3: {
new List<WaitHandle>(); 
   5:  
in CurrentSessionList)
   7:     {
delegate(KeyValuePair<Guid, SessionInfo> sessionInfo)
   9:         {
if (DateTime.Now - sessionInfo.Value.LastActivityTime < Timeout)
  11:             {
return;
  13:             }
try
  15:             {
  16:                 TimeSpan renewDuration = CurrentCallbackList[sessionInfo.Key].Renew();
if (renewDuration.TotalSeconds > 0)
  18:                 {
  19:                     sessionInfo.Value.LastActivityTime += renewDuration;
  20:                 }
else
  22:                 {
true;
  24:                     CurrentCallbackList[session.Key].OnSessionTimeout(sessionInfo.Value);
  25:                 }
  26:             }
catch (CommunicationObjectAbortedException)
  28:             {
true;
return;
  31:             }
  32:         }; 
  33:  
null);
  35:         waitHandleList.Add(result.AsyncWaitHandle);
  36:     } 
  37:  
if (waitHandleList.Count == 0)
  39:     {
return;
  41:     }
  42:             WaitHandle.WaitAll(waitHandleList.ToArray<WaitHandle>());
  43:             ClearSessions();
  44: } 
  45:  
void RenewSession(KeyValuePair<Guid, SessionInfo> session); 
  47:  

首先我定义了一个delegate:RenewSession,来实现表示对单个session的renew操作。在RenewSessions方法中,我们遍历CurrentSessionList中的每个SessionInfo对象,根据LastActivityTime判断是否需要对该Session进行Renew操作(DateTime.Now - sessionInfo.Value.LastActivityTime < Timeout,意味着单单从server来看,Session都尚未过期),如何需要,则通过SessionID从CurrentCallbackList中取出callback对象,调用Renew方法。如何返回的的Timespan大于零,则表明,client端需要延长session的生命周期,则让LastActivityTime 加上该值。如何返回的值小于零,表明session真的过期了,那么通过调用callback对象的OnSessionTimeout方法实现对client的实时的通知,并将SessionInfo对象的IsTimeout 设置为true。等所以得操作结束之后,在将IsTimeout 为true的SessionInfo对象和对应的callback对象从列表中移除。

在这里有3点需要注意:

1)由于在client过多的情况下,CurrentSessionList得数量太多,按照同步的方式逐个进行状态的检测、callback的调用可以需要很长的时间,会严重影响实时性。所以我们采用的是异步的方式,这是通过将操作定义到RenewSession delegate中,并掉用BeginInvoke方法实现的。

2)在调用Callback的Renew方法的时候,很有可以client端的程序已经正常或者非正常关闭,在这种情况下会抛出CommunicationObjectAbortedException异常,我们应该把这种情况视为timeout。所以我们也将IsTimeout 设置为true。

3)我们之所以现在遍历之后才对session进行清理,主要考虑到我们的操作时在对线程环境中执行,如何在并发操作的情况下对集合进行删除,会出现一些意想不到的不同步情况下。我们通过WaitHandle保证所有的并发操作都结束了:我先创建了一个IList<WaitHandle>对象waitHandleList ,将每个基于session对象的异步操作的WaitHandle添加到该列表(waitHandleList.Add(result.AsyncWaitHandle);)通过

WaitHandle.WaitAll(waitHandleList.ToArray<WaitHandle>());保证所有的操作都结束了。

有了SessionManager,我们的Service就显得很简单了:

namespace Artech.SessionManagement.Service
   2: {
   3:     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode =ConcurrencyMode.Multiple)]
class SessionManagementService:ISessionManagement
   5:     {
#region ISessionManagement Members 
   7:  
out TimeSpan timeout)
   9:         {
  10:             timeout = SessionManager.Timeout;
return SessionManager.StartSession(clientInfo);
  12:         } 
  13:  
void EndSession(Guid sessionID)
  15:         {
  16:             SessionManager.EndSession(sessionID);
  17:         } 
  18:  
public IList<SessionInfo> GetActiveSessions()
  20:         {
new List<SessionInfo>(SessionManager.CurrentSessionList.Values.ToArray<SessionInfo>());     
  22:         } 
  23:  
void KillSessions(IList<Guid> sessionIDs)
  25:         {
  26:             SessionManager.KillSessions(sessionIDs);
  27:         } 
  28:  
#endregion
  30:     }
  31: } 
  32:  

基本上就是调用SessionManager对应的方法。

二、Service Hosting

在Artech.SessionManagement.Hosting.Program中的Main()方法中,实际上是做了两件事情:

  • 对SessionManagementService的Host。
  • 通过Timer对象实现对Session列表的定期(5s)轮询。
namespace Artech.SessionManagement.Hosting
   2: {
class Program
   4:     {
string[] args)
   6:         {
typeof(SessionManagementService)))
   8:             { 
delegate
  10:                 {
);
  12:                 };
  13:                 host.Open(); 
  14:  
new Timer(
null, 0, 5000); 
  17:  
  18:                 Console.Read();
  19:             }
  20:         }
  21:     }
  22: } 
  23:  

这是configuration,除了system.serviceModel相关配置外,还定义了配置了session timeout的时间,单位为”分”:

>
>
>
/>
>
>
>
>
/>
>
>
/>
>
>
>
>
>
> 
  19:  

三、如何定义Client

这个service的实现已经完成,我们最后来介绍如何根据service的特点来定义我们的client程序了。我们的client是一个GUI应用(WinForm)。为了简便,我们把所有的逻辑定义在一个facade class上面:SessionUtility。

namespace Artech.SessionManagement.Client
   2: {
class SessionUtility
   4:     {
static SessionUtility()
   6:         {
new SessionCallback();
).CreateChannel();            
   9:         } 
  10:  
static ISessionManagement Channel
  12:         { get; set; } 
  13:  
static ISessionCallback Callback
  15:         { get; set; } 
  16:  
static DateTime LastActivityTime
  18:         { get; set; } 
  19:  
static Guid SessionID
  21:         { get; set; } 
  22:  
static TimeSpan Timeout
  24:         { get; set; } 
  25:  
void StartSession(SessionClientInfo clientInfo)
  27:         {
  28:             TimeSpan timeout;
out timeout);
  30:             Timeout = timeout;
  31:         } 
  32:  
static IList<SessionInfo> GetActiveSessions()
  34:         {
return Channel.GetActiveSessions();
  36:         } 
  37:  
void KillSessions(IList<Guid> sessionIDs)
  39:         {
  40:             Channel.KillSessions(sessionIDs);
  41:         }
  42:     }
  43: } 
  44:  

SessionUtility定义了连个public property:SessionID代表当前session的ID,Timeout代表Session timeout的时间,这两个属性都在StartSession中被初始化,而LastActivityTime代表的是最后一次用户交互的时间。上面的代码和简单,在这里就不多作介绍了。这里需要着重介绍我们的Callback class:

class SessionCallback : ISessionCallback
   2: {
#region ISessionCallback Members 
   4:  
public TimeSpan Renew()
   6:     {
return SessionUtility.Timeout - (DateTime.Now - SessionUtility.LastActivityTime);
   8:     } 
   9:  
void OnSessionKilled(SessionInfo sessionInfo)
  11:     {
, sessionInfo.SessionID.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
  13:         Application.Exit();
  14:     } 
  15:  
void OnSessionTimeout(SessionInfo sessionInfo)
  17:     {
, sessionInfo.SessionID.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information);
  19:         Application.Exit();
  20:     } 
  21:  
#endregion
  23: } 
  24:  

Renew()方法根据Timeout 和LastActivityTime计算出需要对该session延长的时间;OnSessionKilled和OnSessionTimeout在通过MessageBox显示相应的message后将程序退出。

我们简单简单一下本例子提供的client application。具有一个Form。我们把所有的功能集中在该Form中:开始一个新session、获得所有的活动的session列表、强行中止一个或多个Session。

WCF后续之旅(9): 通过WCF双向通信实现Session管理[下篇]

这是StartSession按钮的click event handler:

object sender, EventArgs e)
   2: {
string hostName = Dns.GetHostName();
   4:     IPAddress[] ipAddressList = Dns.GetHostEntry(hostName).AddressList;
string.Empty;
in ipAddressList)
   7:     {
if (address.AddressFamily == AddressFamily.InterNetwork)
   9:         {
;
  11:         }
  12:     }
.ToCharArray()); 
  14:  
this.textBoxUserName.Text.Trim();
string.IsNullOrEmpty(userName))
  17:     {
return;
  19:     } 
  20:  
new SessionClientInfo() { IPAddress = ipAddress, HostName = hostName, UserName = userName };
  22:     SessionUtility.StartSession(clientInfo);
false;
  24: } 

获得当前PC的主机名称和IP地址,连同输入的user name创建SessionClientInfo 对象,调用SessionUtility的StartSession开始新的Session。

“Get All Active Session”,获取当前所有的活动的session,绑定到Datagrid:

object sender, EventArgs e)
   2: {
   3:     IList<SessionInfo> activeSessions = SessionUtility.GetActiveSessions();
this.dataGridViewSessionList.DataSource = activeSessions;
this.dataGridViewSessionList.Rows)
   6:     {
].Value;
].Value = activeSessions.Where(session=> session.SessionID == sessionID).ToList<SessionInfo>()[0].ClientInfo.IPAddress;
].Value = activeSessions.Where(session => session.SessionID == sessionID).ToList<SessionInfo>()[0].ClientInfo.UserName;
  10:     }
  11: } 

“Kill Selected Session”按钮被点击,强行中止选中的Session:

object sender, EventArgs e)
   2: {
new List<Guid>();
this.dataGridViewSessionList.Rows)
   5:     {
)
   7:         {
].Value.ToString());
if (sessionID == SessionUtility.SessionID)
  10:             {
, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
  13:             }
  14:             sessionIDs.Add(sessionID);
  15:         }
  16:     }   
  17:  
  18:     SessionUtility.KillSessions(sessionIDs);           
  19: } 
  20:  

由于不能中止自己当前的Session,所以当选中的列表中包含自己的SessionID,会显示一个messagebox提示不应该杀掉属于自己session。

到这里,实际上还有一件重要的事情没有解决,那就是如何动态修正SessionUtility.LastActivityTime。我们希望的事SessionUtility.LastActivityTime能够真正反映最后一次用户交互的时间。为此我们递归地注册每个control的MouseMove事件:

void RegisterMouseMoveEvent(Control control)
   2: {
delegate
   4:     {
   5:         SessionUtility.LastActivityTime = DateTime.Now;
   6:     }; 
   7:  
in control.Controls)
   9:     {
this.RegisterMouseMoveEvent(child);
  11:     }
  12: } 
  13:  
object sender, EventArgs e)
  15: {
false;
this);
  18: } 
  19:  

如何你运行我们程序,输入user name开始session后,如果在30s内没有任何鼠标操作,下面的MessageBox将会弹出,当你点击OK按钮,程序会退出。
WCF后续之旅(9): 通过WCF双向通信实现Session管理[下篇]

如何你同时开启多个client端程序,点击“Kill Selected Session”按钮,将会列出所有的Active session,就象我们在上面的截图所示的一样。你可以选择某个session,然后通过点击“Kill selected sessions”按钮强行中止它。通过另一个client application将马上得到反馈:弹出下面一个MessageBox。当你点击OK按钮,程序会退出

WCF后续之旅(9): 通过WCF双向通信实现Session管理[下篇]

 

WCF后续之旅: 
WCF后续之旅(1): WCF是如何通过Binding进行通信的 
WCF后续之旅(2): 如何对Channel Layer进行扩展——创建自定义Channel 
WCF后续之旅(3): WCF Service Mode Layer 的中枢—Dispatcher 
WCF后续之旅(4):WCF Extension Point 概览 
WCF后续之旅(5): 通过WCF Extension实现Localization 
WCF后续之旅(6): 通过WCF Extension实现Context信息的传递 
WCF后续之旅(7):通过WCF Extension实现和Enterprise Library Unity Container的集成 
WCF后续之旅(8):通过WCF Extension 实现与MS Enterprise Library Policy Injection Application Block 的集成 
WCF后续之旅(9):通过WCF的双向通信实现Session管理[Part I] 
WCF后续之旅(9): 通过WCF双向通信实现Session管理[Part II] 
WCF后续之旅(10): 通过WCF Extension实现以对象池的方式创建Service Instance 
WCF后续之旅(11): 关于并发、回调的线程关联性(Thread Affinity) 
WCF后续之旅(12): 线程关联性(Thread Affinity)对WCF并发访问的影响 
WCF后续之旅(13): 创建一个简单的WCF SOAP Message拦截、转发工具[上篇] 
WCF后续之旅(13):创建一个简单的SOAP Message拦截、转发工具[下篇] 
WCF后续之旅(14):TCP端口共享 
WCF后续之旅(15): 逻辑地址和物理地址 
WCF后续之旅(16): 消息是如何分发到Endpoint的--消息筛选(Message Filter) 
WCF后续之旅(17):通过tcpTracer进行消息的路由

相关文章: