本帖最后由 天若有情 于 2014-6-16 14:02 编辑
7 L8 `1 H& Y: r! [0 {) C( \) Y/ @* N |, J8 U
本文将向大家介绍如何托管内部WCF服务和公共WCF服务,为了托管内部WCF服务,需要建立一个内部端点,并使用内部角色通信,与在输入端点上托管一个外部服务最主要的区别是内部端点不具有负载均衡特性,而输入端点是挂钩在负载均衡器上的,具有负载均衡功能。, Z0 O- J; }( N- {* t0 d
托管内部WCF服务' y% a' |1 B! O; V, P1 M" `8 U- ?
其实要托管一个内部WCF服务很简单,唯一需要注意的是传递给 ServiceHost 的基地址不同,因为端口号和IP地址要等到运行时才知道,因此需要创建一个主机,动态地传递这些信息给它。
8 W, x0 g2 ^$ U3 E1 m: V r public override bool OnStart()
! J ~) O3 r& Y8 w { c* |% p% B' L* T$ Q! A
// 设置最大并发连接数) @: Q% }, a+ ]# {$ ?
ServicePointManager.DefaultConnectionLimit = 12;
5 L% f5 B' b7 J' G7 j# _ DiagnosticMonitor.Start(“DiagnosticsConnectionString”);% V1 V, S# h3 t* u, }+ {9 o
// For information on handling configuration changes' m2 p9 H# g3 \6 ?, L
// see the MSDN topic at =166357.. }7 z# w9 A( O0 W
RoleEnvironment.Changing += RoleEnvironmentChanging;5 |9 z' g' y3 H2 O) U. }. ?7 l4 }
StartWCFService();: x/ e8 C. i6 N5 W W% i
return base.OnStart();3 I" G" a" a2 `1 K. h
}- r5 ?) }3 C, @% z8 f; Y7 Q$ a
private void StartWCFService()" ]1 n8 z( T2 Y* `
{6 e: {/ A% f) x# c5 r) g w
var baseAddress = String.Format(
- }; T) A4 z( x8 k “net.tcp://{0}”,
# A, ~% G3 s, t RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[雨林木风系统“EchoService”].IPEndpoint
, g8 d" q% y3 M8 l$ I );
8 T7 s; {+ t9 g5 O P var host = new ServiceHost(typeof(EchoService), new Uri(baseAddress));4 |) s: R/ G7 y0 X8 Z" |) v
host.AddServiceEndpoint(typeof(IEchoService), new NetTcpBinding(SecurityMode.None), “echo”);
' t7 g, L8 n* z0 z/ @ host.Open();
5 e' ]5 w( s" L7 s2 ~' a 使用内部WCF服务3 d( q' h4 k- S" a4 G
我想从我另一个托管的服务调用这个服务,下面就是调用这个服务的所有代码:4 Y! O, Y) @$ |) Y( n) u- M5 Y
protected void Button1_Click(object sender, EventArgs e)3 L9 b" Y+ l0 w7 X H5 K
{8 }) q) \3 @9 O9 D4 h5 w
var factory = new ChannelFactory(new NetTcpBinding(SecurityMode.None));
" c& n/ S `% {. O; L9 a( Y var channel = factory.CreateChannel(GetRandomEndpoint());
4 S8 I2 M6 n2 F: s Label1.Text = channel.Echo(TextBox1.Text);# `! T4 O# T; P6 P' o( Z: o; E
}" w' E( S' y+ B; t1 _0 T
private EndpointAddress GetRandomEndpoint()1 s$ ?) X; U9 j7 Q1 _
{
+ H5 M% [6 d+ T! W5 q# o var endpoints = RoleEnvironment.Roles[“WorkerHost”].Instances- G0 U; v- D7 L1 x
.Select(i =》 i.InstanceEndpoints[“EchoService”])
) Y8 `# b$ h' v* d6 x/ A .ToArray();5 V4 R# A5 e7 e7 W8 W. O
var r = new Random(DateTime.Now.Millisecond);- ]/ e6 d; e* N$ t# p
return new EndpointAddress(
) a- X; E6 H. _ String.Format(/ L% T( ^- t+ K1 D0 @
“net.tcp://{0}/echo”," w! i1 m/ f* a% Y. z
endpoints[r.Next(endpoints.Count() - 1)].IPEndpoint)) ~, E7 i4 I! X2 J0 N; {
);
+ J$ }9 G3 l' {' x( R } G. a! A; |1 Q& h
这里唯一要注意的是查询F abric ,确定 WorkerHost 角色中实现了 EchoService 端点,深度系统官网并随机给它们路由请求的所有端点,本来不需要路由请求,我这样做是因为内部端点没有负载均衡功能,我希望在每个 WorkerHost 实例上均匀地分配负载。$ i3 e. [1 Q A! u" j
我发现一个技巧,就是不需要缓存你找到的 IPEndpoint ,因为它已经缓存在API调用中,但根据最佳实践,你应该缓存你的 ChannelFactory 。
3 \) S* O/ d4 h, w! a) ~5 h 托管公共WCF服务* z6 t# y5 Z9 w$ H
托管公共WCF服务也很简单,唯一需要注意的是要使用一个新的行为,为MEX端点处理负载均衡,此外,在你的服务上需要包括一个类属性处理地址过滤不匹配问题。
1 Z2 k- _7 P$ ?# y: ? |