如何解决分布式系统中的跨时区问题[实例篇]
关于如何解决分布式系统中的跨时区问题,上一篇详细介绍了解决方案的实现原理,在这一篇中我们通过一个完整的例子来对这个问题进行深入探讨。尽管《原理篇》中介绍了那么多,解决方案的本质就是:在进行服务调用过程中将客户端的时区信息作为上下文传入服务端,并以此作为时间转换的依据。我们首先定一个具体的类型来定义包含时区信息的上下文类型,我们将这个类型起名为ApplicationContext。
一、通过CallContext实现ApplicationContext
在《通过WCF扩展实现Context信息的传递》一文中,我通过HttpSessionState和CallContext实现了一个ApplicationContext类,为ASP.NET和其他类型的应用提供上下文信息的容器。在这里进行了简化,仅仅实现了基于CallContext的部分。这样一个ApplicationContext类型定义如下:
1:[CollectionDataContract(Namespace="http://www.artech.com/")]
2:publicclassApplicationContext:Dictionary
3:{
4:internalconststringcontextHeaderName="ApplicationContext";
5:internalconststringcontextHeaderNamespace="http://www.artech.com/";
6:
7:privateApplicationContext(){}
8:publicstaticApplicationContextCurrent
9:{
10:get
11:{
12:if(null==CallContext.GetData(typeof(ApplicationContext).FullName))
13:{
14:lock(typeof(ApplicationContext))
15:{
16:if(null==CallContext.GetData(typeof(ApplicationContext).FullName))
17:{
18:varcontext=newApplicationContext();
19:context.TimeZone=TimeZoneInfo.Local;
20:CallContext.SetData(typeof(ApplicationContext).FullName,context);
21:}
22:}
23:}
24:
25:return(ApplicationContext)CallContext.GetData(typeof(ApplicationContext).FullName);
26:}
27:set
28:{
29:CallContext.SetData(typeof(ApplicationContext).FullName,value);
30:}
31:}
32:publicTimeZoneInfoTimeZone
33:{
34:get
35:{
36:returnTimeZoneInfo.FromSerializedString((string)this["__TimeZone"]);
37:}
38:set
39:{
40:this["__TimeZone"]=value.ToSerializedString();
41:}
42:}
43:
44:publicstaticvoidClear()
45:{
46:CallContext.FreeNamedDataSlot(typeof(ApplicationContext).FullName);
47:}
48:}
ApplicationContext继承自Dictionary类型,并被定义成集合数据契约。我们采用Singleton的方式来定义ApplicationContext,当前上下文通过静态方法Current获取。而Current属性返回的是通过CallContext的GetData方法获取,并且Key为类型的全名。便是当前时区的TimeZone属性的类型为TimeZoneInfo,通过序列化和反序列对当前时区进行设置和获取。Clear则将整个ApplicationContext对象从CallContext中移除。
二、创建一个用于时间转化的DateTimeConverter
服务端需要进行两种方式的时间转化,其一是将可户端传入的时间转换成UTC时间,其二就是将从数据库获取的UTC时间转化成基于当前时区上下文的Local时间。为此我定义了如下一个静态的帮助类DateTimeConverter专门进行这两方面的时间转换,而时间转换依据的时区来源于当前ApplicationContext的TimeZone属性。
1:publicstaticclassDateTimeConverter
2:{
3:publicstaticDateTimeConvertTimeToUtc(DateTimedateTime)
4:{
5:if(dateTime.Kind==DateTimeKind.Utc)
6:{
7:returndateTime;
8:}
9:returnTimeZoneInfo.ConvertTimeToUtc(dateTime,ApplicationContext.Current.TimeZone);
10:}
11:
12:publicstaticDateTimeConvertTimeFromUtc(DateTimedateTime)
13:{
14:if(dateTime.Kind==DateTimeKind.Utc)
15:{
16:returndateTime;
17:}
18:returnTimeZoneInfo.ConvertTimeFromUtc(dateTime,ApplicationContext.Current.TimeZone);
19:}
20:}
三、通过WCF扩展实现ApplicationContext的传播
让当前的ApplicationContext在每次服务调用时自动传递到服务端,并作为服务端当前的ApplicationContext,整个过程通过两个步骤来实现:其一是客户端将当前ApplicationContext对象进行序列化,并置于出栈消息的报头(SOAPHeader);其二是服务在接收到请求消息时从入栈消息中提取该报头并进行反序列化,最终将生成的对象作为服务端当前的ApplicationContext。
客户端对当前ApplicationContext输出可以通过WCF的MessageInspector对象来完成。为此,我们实现了IClientMessageInspector接口定义了如下一个自定义的MessageInspector:ContextMessageInspector。在BeforeSendRquest方法中,基于当前ApplicationContext创建了一个MessageHeader,并将其插入出栈消息的报头集合中。该消息报头对应的命名空间和名称为定义在ApplicationContext中的两个常量。
1:publicclassContextMessageInspector:IClientMessageInspector
2:{
3:publicvoidAfterReceiveReply(refMessagereply,objectcorrelationState){}
4:publicobjectBeforeSendRequest(refMessagerequest,IClientChannelchannel)
5:{
6:MessageHeaderheader=newMessageHeader(ApplicationContext.Current);
7:request.Headers.Add(header.GetUntypedHeader(ApplicationContext.contextHeaderName,ApplicationContext.contextHeaderNamespace));
8:returnnull;
9:}
10:}
相应地,服务端对ApplicationContext的接收和设置可以通过WCF的CallContextInitializer来实现。为此,我们实现了ICallContextInitializer接口定义了如下一个自定义的CallContextInitializer:ContextCallContextInitializer。在BeforeInvoke方法中,通过相同的命名空间和名称从入栈消息中提取ApplicationConntext作为当前的ApplicationContext。为了避免当前ApplicationContext用在下一次服务请求处理中(ApplicationContext保存在当前线程的TLS中,而WCF采用线程池的机制处理客户请求),我们在AfterInvoke方法中调用Clear方法将当前ApplicationContext清除。
1:publicclassContextCallContextInitializer:ICallContextInitializer
2:{
3:publicvoidAfterInvoke(objectcorrelationState)
4:{
5:ApplicationContext.Clear();
6:}
7:publicobjectBeforeInvoke(InstanceContextinstanceContext,IClientChannelchannel,Messagemessage)
8:{
9:varindex=message.Headers.FindHeader(ApplicationContext.contextHeaderName,ApplicationContext.contextHeaderNamespace);
10:if(index>=0)
11:{
12:ApplicationContext.Current=message.Headers.GetHeader(index);
13:}
14:returnnull;
15:}
16:}
用于ApplicationContext发送的ContextMessageInspector,和用于ApplicationContext接收的ContextCallContextInitializer,最终我们通过一个EndpointBehavior被应用到WCF运行时框架中。为此我们定义了如下一个自定义的EndpointBehavior:ContextBehavior。
1:publicclassContextBehavior:IEndpointBehavior
2:{
3:publicvoidAddBindingParameters(ServiceEndpointendpoint,BindingParameterCollectionbindingParameters){}
4:publicvoidApplyClientBehavior(ServiceEndpointendpoint,ClientRuntimeclientRuntime)
5:{
6:clientRuntime.MessageInspectors.Add(newContextMessageInspector());
7:}
8:publicvoidApplyDispatchBehavior(ServiceEndpointendpoint,EndpointDispatcherendpointDispatcher)
9:{
10:foreach(DispatchOperationoperationinendpointDispatcher.DispatchRuntime.Operations)
11:{
12:operation.CallContextInitializers.Add(newContextCallContextInitializer());
13:}
14:}
15:publicvoidValidate(ServiceEndpointendpoint){}
16:}
由于ContextBehavior这个终结点行为需要通过培植的方式来使用,我们需要定义它的BehaviorExtensionElement(本质上是一个配置元素):
1:publicclassContextBehaviorElement:BehaviorExtensionElement
2:{
3:publicoverrideTypeBehaviorType
4:{
5:get{returntypeof(ContextBehavior);}
6:}
7:protectedoverrideobjectCreateBehavior()
8:{
9:returnnewContextBehavior();
10:}
11:}
四、建立一个AlertorService来模拟跨时区场景
image到目前为止,所有基础性编程已经完成,我们现在创建一个具体的分布式应用来使用上面定义的类型。为此,我们模拟一个用户提醒服务(AlertorService):我们为某个人创建相应的通知或者提醒,比如什么时候开会,什么时候见客户之类的。首先,所有的Alert条目被最终保存在数据库中,对应的表的结构如右图所示。四个字段分别表示Alert的Id、被通知的人、消息和被触发的时间。这里的表示时间的类型就是我们常用的datetime(不具有时区偏移量信息)。
与这个数据表结构相对应,一个Alert类型被创建出来表示一个具体的Alert条目。Alert被定义成数据契约,下面的代码给出了该类的具体定义。
1:[DataContract]
2:publicclassAlert
3:{
4:[DataMember]
5:publicstringId{get;privateset;}
6:[DataMember]
7:publicstringPerson{get;privateset;}
8:[DataMember]
9:publicstringMessage{get;privateset;}
10:[DataMember]
11:publicDateTimeTime{get;set;}
12:publicAlert(stringpersone,stringmessage,DateTimetime)
13:{
14:this.Id=Guid.NewGuid().ToString();
15:this.Person=persone;
16:this.Message=message;
17:this.Time=time;
18:}
19:}
然后我们定义服务契约:IAlert接口。该结构定义了两个操作成员,CreateNewAlert用于创建一个信息的Alert条目;而GetAlerts则用于获取某个人对应的所有Alert列表。
1:[ServiceContract(Namespace="http://www.artech.com/")]
2:publicinterfaceIAlertor
3:{
4:[OperationContract]
5:voidCreateNewAlert(Alertalert);
6:[OperationContract]
7:IEnumerableGetAlerts(stringperson);
8:}
下面是实现上面这个服务契约的具体服务的实现:AlertorService。DbHelper是我创建的一个简单的进行数据操作的帮助类,AlertorService用它来执行一段参数化的SQL语句,以及执行一段SELECT语句返回一个DbDataReader。对此你无需过多关注没,你需要关注的是在CreateNewAlert方法中,在进行数据保存之前先调用了DateTimeConverter的ConvertTimeToUtc将基于客户端时区的本地时间转化成了UTC时间;而在GetAlerts方法中在将从数据库中返回的Alert列表返回给客户端的时候,调用了DateTimeConverter的ConvertTimeFromUtc将UTC时间转化成了基于客户端时区的本地时间。
1:publicclassAlertorService:IAlertor
2:{
3:privateDbHelperhelper=newDbHelper("TestDb");
4:publicvoidCreateNewAlert(Alertalert)
5:{
6:alert.Time=DateTimeConverter.ConvertTimeToUtc(alert.Time);
7:varparameters=newDictionary();
8:parameters.Add("@id",alert.Id);
9:parameters.Add("@person",alert.Person);
10:parameters.Add("@message",alert.Message);
11:parameters.Add("@time",alert.Time);
12:helper.ExecuteNoQuery("INSERTINTOdbo.Alert(Id,Person,Message,Time)VALUES(@id,@person,@message,@time)",parameters);
13:}
14:publicIEnumerableGetAlerts(stringperson)
15:{
16:varparameters=newDictionary();
17:parameters.Add("@person",person);
18:using(varwww.wang027.comreader=helper.ExecuteReader("SELECTPerson,Message,TimeFROMdbo.AlertWHEREPerson=@person",parameters))
19:{
20:while(reader.Read())
21:{
22:yieldreturnnewAlert(reader[0].ToString(),reader[1].ToString(),DateTimeConverter.ConvertTimeFromUtc((DateTime)reader[2]));
23:}
24:}
25:}
26:}
在对上面的服务进行寄宿的时候,采用了如下的配置,将上面创建的ContextBehavior终结点行为应用到了相应的终结点上。
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18: 19:binding="ws2007HttpBinding"bindingConfiguration=""contract="Artech.TimeConversion.Service.Interface.IAlertor"/>
20:
21:
22:
23:
客户端在通过如下的配置将ContextBehavior应用到用于服务调用的终结点上:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12: 13:binding="ws2007HttpBinding"bindingConfiguration=""contract="Artech.TimeConversion.Service.Interface.IAlertor"
14:name="alertservice"/>
15:
16:
17:
18:
19:
20:
21:
22:
而下面的代码代表了客户端程序:我们为某个人(Foo)创建了三个Alert,主要这里指定的时间的DateTimeKind为默认的DateTimeKind.Unspecified。然后调用服务或者这三条Alert对象,并将消息的时间打印出来。
1:publicclassProgram
2:{
3:staticvoidMain(string[]args)
4:{
5:CreateAlert("Foo","WeeklyMeetingwithTestingTeam",newDateTime(2010,9,1,8,0,0));
6:CreateAlert("Foo","ArchitectureandDesignTraining",newDateTime(2010,9,2,8,0,0));
7:CreateAlert("Foo","NewStuffOrientaion",newDateTime(2010,9,3,8,0,0));
8:
9:foreach(varalertinGetAlerts("Foo"))
10:{
11:Console.WriteLine("Alert:\t{0}",alert.Message);
12:Console.WriteLine("Time:\t{0}\n",alert.Time);
13:}
14:
15:Console.Read();
16:}
17:
18:staticIEnumerableGetAlerts(stringperson)
19:{
20:using(ChannelFactorychannelFactory=newChannelFactory("alertservice"))
21:{
22:IAlertoralertor=channelFactory.CreateChannel();
23:using(alertorasIDisposable)
24:{
25:returnalertor.GetAlerts(person);
26:}
27:}
28:}
29:staticvoidCreateAlert(stringperson,stringmessage,DateTimetime)
30:{
31:Alertalert=newAlert(person,message,time);
32:using(ChannelFactorychannelFactory=newChannelFactory("alertservice"))
33:{
34:IAlertoralertor=channelFactory.CreateChannel();
35:using(alertasIDisposable)
36:{
37:alertor.CreateNewAlert(alert);
38:}
39:}
40:}
41:}
image运行上面的程序之后。服务端数据库中被添加的三条Alert纪录对应的时间,会以UTC形式存储。如左图所示,数据表中的时间比我们指定的的时间早8个小时。
下面是客户端的输出结果,可见Alert的提醒时间依然是基于本地时区的时间,这达到了我们在《原理篇》提出的要求:客户端应用根本不用考虑时区问题,就像是一个单纯的本地应用一样。客户端调用服务传入的时间是DateTimeKind.Local时间或者DateTimeKind.Unspecified时间,同理通过服务调用返回的时间也应该是基于客户端所在时区的时间。
1:Alert:NewStuffOrientaion
2:Time:9/3/20108:00:00AM
3:
4:Alert:WeeklyMeetingwithTestingTeam
5:Time:9/1/20108:00:00AM
6:
7:Alert:ArchitectureandDesignTraining
8:Time:9/2/20108:00:00AM
9:
|
|