本帖最后由 天若有情 于 2014-6-16 14:02 编辑
+ o$ X ]% {( \: a
: O/ l# d, B& s$ s3 h4 A 本文将向大家介绍如何托管内部WCF服务和公共WCF服务,为了托管内部WCF服务,需要建立一个内部端点,并使用内部角色通信,与在输入端点上托管一个外部服务最主要的区别是内部端点不具有负载均衡特性,而输入端点是挂钩在负载均衡器上的,具有负载均衡功能。
# R8 [* Z- a9 { L% H Q 托管内部WCF服务
5 h( Z& D& t+ K0 o. S% T; t" a 其实要托管一个内部WCF服务很简单,唯一需要注意的是传递给 ServiceHost 的基地址不同,因为端口号和IP地址要等到运行时才知道,因此需要创建一个主机,动态地传递这些信息给它。
$ B0 d6 u' v3 i+ n: Q public override bool OnStart()
0 J8 b6 K+ J1 m {9 M$ I- n* @1 B' _$ m" o
// 设置最大并发连接数7 n, N# o! t% j7 T [
ServicePointManager.DefaultConnectionLimit = 12;) x6 ]6 ~5 \! a5 u
DiagnosticMonitor.Start(“DiagnosticsConnectionString”);( k: n8 }# Q, l
// For information on handling configuration changes% [' e l$ a# [* p- W$ Z% g
// see the MSDN topic at =166357.) p7 u# q q) Z& x& W0 F
RoleEnvironment.Changing += RoleEnvironmentChanging;" H- m9 k1 Q+ N
StartWCFService();
$ C* b9 w m! @1 [. {* |( C return base.OnStart();
, o3 T" b+ {: q }/ U- d; o" I% A; g( _( o
private void StartWCFService()
; ] o) v5 Z9 S" Z$ v9 n5 D {
% r+ n3 X3 o) h/ }7 M: S var baseAddress = String.Format(
+ J; z, d( x2 y “net.tcp://{0}”,# e2 U5 j& N4 c W6 t9 z ]% a
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[雨林木风系统“EchoService”].IPEndpoint% `& Y; [% d( y7 [5 K# U
); C7 `- w2 ]! X k8 K4 ^/ U) U
var host = new ServiceHost(typeof(EchoService), new Uri(baseAddress));# [ b5 l0 n3 c- p: q! I' s
host.AddServiceEndpoint(typeof(IEchoService), new NetTcpBinding(SecurityMode.None), “echo”);2 Z! |, H# m+ ^6 } w) w
host.Open();
1 g! f( S3 E6 B: i1 Z 使用内部WCF服务
! U% C" g" b0 F1 T( q+ ~ 我想从我另一个托管的服务调用这个服务,下面就是调用这个服务的所有代码:' {# k$ x! I' Z# g- G
protected void Button1_Click(object sender, EventArgs e)
" o# H e2 ]* W4 l {! I' E8 i- `6 Y* ^* q& l x
var factory = new ChannelFactory(new NetTcpBinding(SecurityMode.None));6 _& G# ~% a5 K$ U( y$ n
var channel = factory.CreateChannel(GetRandomEndpoint());, K1 l+ [% U4 m7 }! W: t% Q, U
Label1.Text = channel.Echo(TextBox1.Text);
% U$ ^: _3 Y+ y6 M }
5 L, ^1 M' S+ z private EndpointAddress GetRandomEndpoint()9 o- N7 D, ^' z* k2 ]5 Q# V; N! n
{* y, K. k6 h0 M& u9 k: F
var endpoints = RoleEnvironment.Roles[“WorkerHost”].Instances3 s' a1 {) m5 c# `1 O% \
.Select(i =》 i.InstanceEndpoints[“EchoService”])
% | a! w7 L8 f7 y4 Z .ToArray();
" {! f0 C2 r1 g2 O' y var r = new Random(DateTime.Now.Millisecond);
( R0 b4 g0 B) S7 V* C: Q$ A return new EndpointAddress(5 V/ c, j0 |2 V2 O3 j
String.Format(# V. _3 F7 A7 o7 g" p
“net.tcp://{0}/echo”,1 }' I( G( N& [0 }* R' V
endpoints[r.Next(endpoints.Count() - 1)].IPEndpoint); j1 b$ k+ i2 U$ B4 `. c
);6 Y# U$ k# O- e% O6 s
}, Y% l7 h e5 ~+ l; y7 D) l# V
这里唯一要注意的是查询F abric ,确定 WorkerHost 角色中实现了 EchoService 端点,深度系统官网并随机给它们路由请求的所有端点,本来不需要路由请求,我这样做是因为内部端点没有负载均衡功能,我希望在每个 WorkerHost 实例上均匀地分配负载。- ?9 ]( @2 A" ^+ ]2 `
我发现一个技巧,就是不需要缓存你找到的 IPEndpoint ,因为它已经缓存在API调用中,但根据最佳实践,你应该缓存你的 ChannelFactory 。5 c4 H6 n6 V/ T) w" a/ O! F
托管公共WCF服务. Y7 ^' S, ?2 N |2 y
托管公共WCF服务也很简单,唯一需要注意的是要使用一个新的行为,为MEX端点处理负载均衡,此外,在你的服务上需要包括一个类属性处理地址过滤不匹配问题。% h. ^ F3 L' \$ B
|