本帖最后由 天若有情 于 2014-6-16 14:02 编辑 $ L l5 g# g( v
8 h, J4 }# ^7 i* v
本文将向大家介绍如何托管内部WCF服务和公共WCF服务,为了托管内部WCF服务,需要建立一个内部端点,并使用内部角色通信,与在输入端点上托管一个外部服务最主要的区别是内部端点不具有负载均衡特性,而输入端点是挂钩在负载均衡器上的,具有负载均衡功能。
J+ q4 I7 ^+ t$ P% | 托管内部WCF服务' p; o3 p3 i# |/ w. R
其实要托管一个内部WCF服务很简单,唯一需要注意的是传递给 ServiceHost 的基地址不同,因为端口号和IP地址要等到运行时才知道,因此需要创建一个主机,动态地传递这些信息给它。6 A# D1 d0 J0 z" {4 D4 z
public override bool OnStart()3 }: }2 {$ i4 \, F8 ]
{% g6 M. o% u6 G/ [# E" ?" G6 @1 }
// 设置最大并发连接数2 P+ J9 A) X: J* ^8 a7 T. Y3 ]
ServicePointManager.DefaultConnectionLimit = 12; ]0 Q5 ]9 }' m9 r; ^
DiagnosticMonitor.Start(“DiagnosticsConnectionString”);
. d3 h8 T) Q6 o // For information on handling configuration changes, y5 b8 v: M8 z- p4 P" I; M4 o
// see the MSDN topic at =166357.2 k( @+ @" f/ l$ A! x
RoleEnvironment.Changing += RoleEnvironmentChanging;
+ [: j1 q- r9 q; g% A8 D: n StartWCFService();
K1 ~2 [. L7 @- q' e; @8 A return base.OnStart();
# f4 h$ P- u7 f `; x }" V4 E; [5 ?/ d, f: R
private void StartWCFService()2 J% r, P2 Q4 H* r+ L
{, E0 h) Y( }0 y% Q+ d
var baseAddress = String.Format(' T7 \ _# i I: r
“net.tcp://{0}”,3 q/ U# b/ Q/ l: j; O
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[雨林木风系统“EchoService”].IPEndpoint
5 u, U0 @$ v/ B" U( D+ n5 J );! ]/ B2 G. b9 P8 t
var host = new ServiceHost(typeof(EchoService), new Uri(baseAddress));! F8 k' Z* Z+ m' F" j
host.AddServiceEndpoint(typeof(IEchoService), new NetTcpBinding(SecurityMode.None), “echo”);" x4 w3 _& R' O/ u# F4 }: W2 n
host.Open();( c/ e; P4 u, }) \+ n$ s
使用内部WCF服务" k4 U9 @) l/ N _+ X& o8 h
我想从我另一个托管的服务调用这个服务,下面就是调用这个服务的所有代码:6 F: O0 P% i# ~! v7 ~4 S
protected void Button1_Click(object sender, EventArgs e)2 y) `$ V. Y# Y1 r
{+ D- G/ `1 G+ L/ p
var factory = new ChannelFactory(new NetTcpBinding(SecurityMode.None));
) e" x2 E# _3 C0 d# G$ ^3 ~ X# D, ?/ R var channel = factory.CreateChannel(GetRandomEndpoint());; P7 O) I4 T4 P) @. W
Label1.Text = channel.Echo(TextBox1.Text);! z' X4 m3 L/ J7 o: {; b
}
7 O2 t) |$ k2 y/ T. h/ O private EndpointAddress GetRandomEndpoint()0 `9 W& d, g" h/ M& E
{& U+ L J0 R2 d7 d
var endpoints = RoleEnvironment.Roles[“WorkerHost”].Instances
5 c& j' V# U2 }) l7 S. p6 A+ g .Select(i =》 i.InstanceEndpoints[“EchoService”])! A1 R% h: G* s; ~3 b
.ToArray();. g" ?/ Q2 }* M
var r = new Random(DateTime.Now.Millisecond);; {1 Y+ q: s9 ^
return new EndpointAddress() b0 @0 T, R7 {: e' F) B/ y" d7 N* G
String.Format(
: O& G; O2 @* M “net.tcp://{0}/echo”,
; w& {" R' z( j0 T8 A" w endpoints[r.Next(endpoints.Count() - 1)].IPEndpoint)$ Y- z$ X2 n9 l
);
* Q* x8 A, e9 C: `6 ?' \& k }" c7 L* b3 w0 l
这里唯一要注意的是查询F abric ,确定 WorkerHost 角色中实现了 EchoService 端点,深度系统官网并随机给它们路由请求的所有端点,本来不需要路由请求,我这样做是因为内部端点没有负载均衡功能,我希望在每个 WorkerHost 实例上均匀地分配负载。3 ]8 ?& n4 W( o J
我发现一个技巧,就是不需要缓存你找到的 IPEndpoint ,因为它已经缓存在API调用中,但根据最佳实践,你应该缓存你的 ChannelFactory 。
9 F" |3 N7 A) A 托管公共WCF服务
0 t1 y+ d& D2 U) c+ b' }1 ?- m 托管公共WCF服务也很简单,唯一需要注意的是要使用一个新的行为,为MEX端点处理负载均衡,此外,在你的服务上需要包括一个类属性处理地址过滤不匹配问题。
/ J% i% N8 N) j |