WCF后续之旅(10): 通过WCF Extension实现以对象池的方式创建Service Instance
一、实现原理
和本系列前两篇文章(WCF和Unity Appliation Block集成;WCF和Policy Injection Application Block集成)一样,涉及的是service instance的提供的问题,所以,我们也是通过自定义InstanceProvider来实现以对象池的机制创建service instance的目的。
四、PooledInstnaceProvider的创建
1: namespace Artech.WCFExtensions
2: {
3: public interface IPooledObject
4: {
5: bool IsBusy
6: { get; set; }
7: }
8: }
II、WeakReferenceCollection和WeakReferenceDictionary
1: namespace Artech.WCFExtensions
2: {
3: public class WeakReferenceCollection:List<WeakReference>
4: {}
5:
6: public class WeakReferenceDictionary : Dictionary<Type, WeakReferenceCollection>
7: {}
8: }
1: namespace Artech.WCFExtensions
2: {
3: public static class PooledInstanceLocator
4: {
5: internal static WeakReferenceDictionary ServiceInstancePool
6: { get; set; }
7:
8: static PooledInstanceLocator()
9: {
10: ServiceInstancePool = new WeakReferenceDictionary();
11: }
12:
13: public static IPooledObject GetInstanceFromPool(Type serviceType)
14: {
15: if(!serviceType.GetInterfaces().Contains(typeof(IPooledObject)))
16: {
17: throw new InvalidCastException("InstanceType must implement Artech.WCFExtensions.IPooledInstance");
18: }
19:
20: if (!ServiceInstancePool.ContainsKey(serviceType))
21: {
22: ServiceInstancePool[serviceType] = new WeakReferenceCollection();
23: }
24:
25: WeakReferenceCollection instanceReferenceList = ServiceInstancePool[serviceType] ;
26:
27: lock (serviceType)
28: {
29: IPooledObject serviceInstance =null;
30: foreach (WeakReference weakReference in instanceReferenceList)
31: {
32: serviceInstance = weakReference.Target as IPooledObject;
33: if (serviceInstance != null && !serviceInstance.IsBusy)
34: {
35: serviceInstance.IsBusy = true;
36: return serviceInstance;
37: }
38: }
39:
40: serviceInstance = Activator.CreateInstance(serviceType) as IPooledObject;
41: serviceInstance.IsBusy = true;
42: instanceReferenceList.Add(new WeakReference(serviceInstance));
43: return serviceInstance;
44: }
45: }
46:
47: public static void Scavenge()
48: {
49: foreach (Type serviceType in ServiceInstancePool.Keys)
50: {
51: lock (serviceType)
52: {
53: WeakReferenceCollection instanceReferenceList = ServiceInstancePool[serviceType];
54: for (int i = instanceReferenceList.Count - 1; i > -1; i--)
55: {
56: if (instanceReferenceList[i].Target == null)
57: {
58: instanceReferenceList.RemoveAt(i);
59: }
60: }
61:
62: }
63: }
64: }
65:
66: public static void ReleaseInstanceToPool(IPooledObject instance)
67: {
68: instance.IsBusy = false;
69: }
70: }
71: }
72:
1: namespace Artech.WCFExtensions
2: {
3: class PooledInstanceProvider : IInstanceProvider
4: {
5:
6: public object GetInstance(InstanceContext instanceContext, Message message)
7: {
8: return PooledInstanceLocator.GetInstanceFromPool(instanceContext.Host.Description.ServiceType);
9: }
10:
11: public object GetInstance(InstanceContext instanceContext)
12: {
13: return this.GetInstance(instanceContext, null);
14: }
15:
16: public void ReleaseInstance(InstanceContext instanceContext, object instance)
17: {
18: PooledInstanceLocator.ReleaseInstanceToPool(instance as IPooledObject);
19: }
20: }
21: }
V、为自定义InstanceProvider定义Behavior
1: namespace Artech.WCFExtensions
2: {
3: public class PooledInstanceBehaviorAttribute : Attribute, IContractBehavior, IContractBehaviorAttribute
4: {
5: public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters){ }
6: public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime){ }
7: public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
8: {
9: dispatchRuntime.InstanceProvider = new PooledInstanceProvider();
10: }
11: public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint){ }
12: public Type TargetContract
13: {
14: get { return null; }
15: }
16: }
17: }
三、将PooledInstanceProvider应用到WCF应用中
I、Contract:Contracts.IService
1: namespace Contracts
2: {
3: [ServiceContract]
4: [PooledInstanceBehavior]
5: public interface IService : IPooledObject
6: {
7: [OperationContract(IsOneWay =true)]
8: void DoSomething();
9: }
10: }
1: namespace Services
2: {
3: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
4: public class Service : IService
5: {
6: static int count;
7: public Service()
8: {
9: Interlocked.Increment(ref count);
10: Console.WriteLine("{0}: Service instance is constructed!", count);
11: }
12: public void DoSomething(){ }
13: public bool IsBusy
14: { get; set; }
15: }
16: }
1: public Service()
2: {
3: Interlocked.Increment(ref count);
4: Console.WriteLine("{0}: Service instance is constructed!", count);
5: }
1: namespace Hosting
2: {
3: class Program
4: {
5: static Timer ScavengingTimer;
6:
7: static void Main(string[] args)
8: {
9: using (ServiceHost host = new ServiceHost(typeof(Service)))
10: {
11: host.Opened += delegate
12: {
13: Console.WriteLine("Service has been started up!");
14: };
15:
16: host.Open();
17:
18: ScavengingTimer = new Timer(delegate
19: {
20: PooledInstanceLocator.Scavenge();
21: }, null, 0, 5000);
22:
23: Console.Read();
24:
25: }
26: }
27: }
28: }
29:
除了对service进行Host之外,Main()方法还通过一个Timer对象实现对对象池的清理工作(调用PooledInstanceLocator.Scavenge();),时间间隔是5s。
下面是configuration:
1: <?xml version="1.0" encoding="utf-8" ?>
2: <configuration>
3: <system.serviceModel>
4: <services>
5: <service name="Services.Service">
6: <endpoint binding="basicHttpBinding" contract="Contracts.IService" />
7: <host>
8: <baseAddresses>
9: <add baseAddress="https://127.0.0.1/service" />
10: </baseAddresses>
11: </host>
12: </service>
13: </services>
14: </system.serviceModel>
15: </configuration>
1: namespace Clients
2: {
3: class Program
4: {
5: static void Main(string[] args)
6: {
7: using (ChannelFactory<IService> channelFactory = new ChannelFactory<IService>("service"))
8: {
9: for (int i = 1; i <= 10; i++)
10: {
11: Console.WriteLine("{0}: invocate service!", i);
12: channelFactory.CreateChannel().DoSomething();
13: Thread.Sleep(1000);
14: }
15: }
16:
17: Console.Read();
18: }
19: }
20: }
1: namespace Contracts
2: {
3: [ServiceContract]
4: //[PooledInstanceBehavior]
5: public interface IService : IPooledObject
6: {
7: [OperationContract(IsOneWay =true)]
8: void DoSomething();
9: }
10: }
可见在没有运用PooledInstanceBehavior情况下,service instance的创建真正使“PerCall”。我们将PooledInstanceBehavior重新加上,然后通过在DoSomething方法中加上下面的代码延长该方法执行的时间:
1: namespace Services
2: {
3: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
4: public class Service:IService
5: {
6: public void DoSomething()
7: {
8: Thread.Sleep(2000);
9: }
10: }
11: }
由于我们将DoSomething方法的执行延长至2s,在这种情况下,由于client端的service掉用的间隔是1s,所有当第二次service调用抵达之后,第一次创建的service
instance还没有被释放,所以需要重新创建新的service instance。当第三次service调用时,第一个service
instance已经释放,以此类推,永远只需要两个service instance。这和上面的结果一致。
1: namespace Hosting
2: {
3: class Program
4: {
5: static Timer ScavengingTimer;
6: static Timer GCTimer;
7: static void Main(string[] args)
8: {
9: using (ServiceHost host = new ServiceHost(typeof(Service)))
10: {
11: host.Opened += delegate
12: {
13: Console.WriteLine("Service has been started up!");
14: };
15:
16: host.Open();
17:
18: ScavengingTimer = new Timer(delegate
19: {
20: PooledInstanceLocator.Scavenge();
21: }, null, 0, 5000);
22:
23: GCTimer = new Timer(delegate
24: {
25: GC.Collect();
26: }, null, 0, 500);
27:
28: Console.Read();
29:
30: }
31: }
32: }
33: }
34:
1: namespace Services
2: {
3: [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
4: public class Service:IService
5: {
6:
7: #region IService Members
8:
9: public void DoSomething()
10: {
11: Thread.Sleep(500);
12: }
13:
14: #endregion
15: }
16: }
那么现在的输出结果将会是这样:
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进行消息的路由
微信公众账号:大内老A
微博:www.weibo.com/artech
如果你想及时得到个人撰写文章以及着作的消息推送,或者想看看个人推荐的技术资料,可以扫描左边二维码(或者长按识别二维码)关注个人公众号(原来公众帐号蒋金楠的自媒体将会停用)。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
最后更新:2017-10-30 17:04:34