我正在了解 WCF 路由服务可以做什么。仍处于“摆弄它看看它能做什么”阶段。
我对路由服务的理解是,当消息通过时,该服务将尝试将其传递到备份列表中首先出现的端点。如果失败,它将继续尝试下一个,然后再尝试下一个,直到有东西起作用或者没有什么可以尝试的。
我想做的是访问该失败事件,以便我可以:
- 记录失败
- 通过电子邮件发送端点发生故障的通知
- 可以选择从备份列表中删除端点,这样就不会减慢未来消息流经系统的速度
无法找到如何扩展 WCF 框架来处理此特定事件。
这是 WCF 路由服务可以做的事情吗?任何朝着正确方向的推动将不胜感激。
目前,我有 30 个动态生成的路由服务托管在 IIS(或更准确地说,Visual Studio 2010 的 ASP.NET 开发服务器)下。我正在 Global.asax 中设置服务的路由,如下所示。
protected void Application_Start(object sender, EventArgs e)
{
List<Type> serviceTypes = ServiceUtility.GetServiceTypes();
foreach (Type st in serviceTypes)
{
string route = String.Format("Services/{0}.svc", ServiceUtility.GetServiceName(st));
RouteTable.Routes.Add(new ServiceRoute(route, new RoutingServiceHostFactory(st), typeof(System.ServiceModel.Routing.RoutingService)));
}
}
ServiceUtility 和 RoutingServiceHostFactory 是自定义类。请注意,IPolicyService 是我感兴趣的程序集中的 WCF 服务契约接口。
public static class ServiceUtility
{
public static List<Type> GetServiceTypes()
{
Type policyInterfaceType = typeof(IPolicyService);
Assembly serviceContractsAssembly = Assembly.GetAssembly(policyInterfaceType);
Type[] serviceContractsAssemblyTypes = serviceContractsAssembly.GetTypes();
List<Type> serviceTypes = new List<Type>();
foreach (Type t in serviceContractsAssemblyTypes)
{
if (!t.IsInterface)
continue;
object[] attrib = t.GetCustomAttributes(typeof(ServiceContractAttribute), false);
if (attrib == null || attrib.Length <= 0)
continue;
serviceTypes.Add(t);
}
return serviceTypes;
}
// Other stuff
}
我正在生成我的 ServiceHosts,如下所示。为了简洁起见,我省略了一些辅助方法。
public class RoutingServiceHostFactory : ServiceHostFactory
{
private Type BackendServiceType { get; set; }
private Binding BackendServiceBinding { get; set; }
public RoutingServiceHostFactory(Type backendServiceType)
{
this.BackendServiceType = backendServiceType;
this.BackendServiceBinding = ServiceUtility.GetBinding(this.BackendServiceType);
}
private const string DOMAIN_LIVE = "http://localhost:2521/";
private const string DOMAIN_DEAD_1 = "http://localhost:2522/";
private const string DOMAIN_DEAD_2 = "http://localhost:2524/";
private const string DOMAIN_DEAD_3 = "http://localhost:2525/";
private const string DOMAIN_DEAD_4 = "http://localhost:2526/";
private const string DOMAIN_DEAD_5 = "http://localhost:2527/";
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);
this.BindEndpoints(host, baseAddresses);
this.ConfigureRoutingBehavior(host);
this.ConfigureServiceMetadataBehavior(host);
this.ConfigureDebugBehavior(host);
host.Description.Behaviors.Add(new RoutingServiceErrorHandlerInjector());
return host;
}
// Other Stuff
private void ConfigureRoutingBehavior(ServiceHost host)
{
string deadAddress1 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_1, this.BackendServiceType);
string deadAddress2 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_2, this.BackendServiceType);
string deadAddress3 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_3, this.BackendServiceType);
string deadAddress4 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_4, this.BackendServiceType);
string deadAddress5 = ServiceUtility.GetServiceUrl(DOMAIN_DEAD_5, this.BackendServiceType);
string realAddress = ServiceUtility.GetServiceUrl(DOMAIN_LIVE, this.BackendServiceType);
RoutingConfiguration rc = new RoutingConfiguration();
ContractDescription contract = new ContractDescription("IRequestReplyRouter");
ServiceEndpoint deadDestination1 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress1));
ServiceEndpoint deadDestination2 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress2));
ServiceEndpoint deadDestination3 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress3));
ServiceEndpoint deadDestination4 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress4));
ServiceEndpoint deadDestination5 = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(deadAddress5));
ServiceEndpoint realDestination = new ServiceEndpoint(contract, this.BackendServiceBinding, new EndpointAddress(realAddress));
List<ServiceEndpoint> backupList = new List<ServiceEndpoint>();
backupList.Add(deadDestination1);
backupList.Add(deadDestination2);
backupList.Add(deadDestination3);
backupList.Add(deadDestination4);
backupList.Add(deadDestination5);
backupList.Add(realDestination);
rc.FilterTable.Add(new MatchAllMessageFilter(), backupList);
RoutingBehavior rb = new RoutingBehavior(rc);
host.Description.Behaviors.Add(rb);
}
// Other Stuff
}
端口 2521 在另一端有一个实际网站,正在托管一些 WCF 服务。上面提到的其他端口没有任何监听。
对于上下文,这是我的路由站点的 Web.config。注意,暂停之类的只是我胡闹的结果,别太当真。
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<bindings>
<wsHttpBinding>
<binding
name="TestBinding"
allowCookies="True"
closeTimeout="00:04:00"
openTimeout="00:00:10"
receiveTimeout="00:05:00"
sendTimeout="00:05:00"
maxReceivedMessageSize="15728640">
<security>
<message establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
</configuration>
EDIT
为了回应下面 TheDoctor 的回答,我认为我应该扩展自从我最初发布以来我一直在尝试的解决方案所做的事情。我尝试过实现 IErrorHandler 接口。然而,我并没有那么幸运。
请注意,在上面的示例中,我的 RoutingServiceHostFactory 发生了轻微的变化。我现在将 RoutingServiceErrorHandlerInjector 行为添加到服务描述中。请注意,出于说明目的,我还在备份列表中添加了额外的死端点。
public class RoutingServiceErrorHandlerInjector : IServiceBehavior
{
#region IServiceBehavior Members
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
{
chanDisp.ErrorHandlers.Add(new RoutingServiceErrorHandler());
}
}
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
#endregion
}
public class RoutingServiceErrorHandler : IErrorHandler
{
#region IErrorHandler Members
public bool HandleError(Exception error)
{
throw new NotImplementedException(error.Message, error);
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
throw new NotImplementedException(error.Message, error);
}
#endregion
}
我的期望是我应该触发 deadDestination1 到 deadDestination5 的 ProvideFault 或 HandleError 事件。我在调试器中的上面的 NotImplementedExceptions 上设置了断点。但该代码从未被激活。来电最终使其到达备份列表末尾的真实地址,并且我用来测试此 RoutingService 的客户端/服务器应用程序运行良好。通信速度较慢,但仍在超时限制之内。
但是,如果我注释掉该行backupList.Add(realDestination);
从上面的ConfigureRoutingBehavior方法,然后执行RoutingServiceErrorHandler.ProvideFault方法...但它只包含与deadDestination5相关的信息。任何可能为 deadDestination1 到 deadDestination4 生成的异常或错误对我来说都消失了。
此外,我尝试使用 RedGate 调试器逐步执行 RoutingService 的反射代码。这对我来说很棘手,因为我不习惯调试优化的代码,所以几乎没有任何变量可供我实际读取。但从目击的角度来看,下面的逻辑是这样的:
// This has been taken from System.ServiceModel.Routing.RoutingService
// via the RedGate decompiler - unsure about it's ultimate accuracy.
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed), ServiceBehavior(AddressFilterMode=AddressFilterMode.Any, InstanceContextMode=InstanceContextMode.PerSession, UseSynchronizationContext=false, ValidateMustUnderstand=false)]
public sealed class RoutingService : ISimplexDatagramRouter, ISimplexSessionRouter, IRequestReplyRouter, IDuplexSessionRouter, IDisposable
{
[OperationBehavior(Impersonation=ImpersonationOption.Allowed), TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
IAsyncResult IRequestReplyRouter.BeginProcessRequest(Message message, AsyncCallback callback, object state)
{
return this.BeginProcessRequest<IRequestReplyRouter>(message, callback, state);
}
private IAsyncResult BeginProcessRequest<TContract>(Message message, AsyncCallback callback, object state)
{
IAsyncResult result;
try
{
System.ServiceModel.Routing.FxTrace.Trace.SetAndTraceTransfer(this.ChannelExtension.ActivityID, true);
result = new ProcessRequestAsyncResult<TContract>(this, message, callback, state);
}
catch (Exception exception)
{
if (TD.RoutingServiceProcessingFailureIsEnabled())
{
TD.RoutingServiceProcessingFailure(this.eventTraceActivity, OperationContext.Current.Channel.LocalAddress.ToString(), exception);
}
throw;
}
return result;
}
}
System.ServiceModel.Routing.ProcessRequestAsyncResult 的相关部分如下所示。这些也是通过RedGate调试的,所以无法修改。我相信 RedGate 和 Microsoft 发布的源代码是准确的。 #他说得很可疑
internal class ProcessRequestAsyncResult<TContract> : TransactedAsyncResult
{
public ProcessRequestAsyncResult(RoutingService service, Message message, AsyncCallback callback, object state) : base(callback, state)
{
this.allCompletedSync = true;
this.service = service;
this.messageRpc = new System.ServiceModel.Routing.MessageRpc(message, OperationContext.Current, service.ChannelExtension.ImpersonationRequired);
if (TD.RoutingServiceProcessingMessageIsEnabled())
{
TD.RoutingServiceProcessingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, message.Headers.Action, this.messageRpc.OperationContext.EndpointDispatcher.EndpointAddress.Uri.ToString(), (this.messageRpc.Transaction != null) ? "True" : "False");
}
try
{
EndpointNameMessageFilter.Set(this.messageRpc.Message.Properties, service.ChannelExtension.EndpointName);
this.messageRpc.RouteToSingleEndpoint<TContract>(this.service.RoutingConfig);
}
catch (MultipleFilterMatchesException exception)
{
throw System.ServiceModel.Routing.FxTrace.Exception.AsError(new ConfigurationErrorsException(System.ServiceModel.Routing.SR.ReqReplyMulticastNotSupported(this.messageRpc.OperationContext.Channel.LocalAddress), exception));
}
while (this.StartProcessing())
{
}
}
private bool StartProcessing()
{
bool flag = false;
SendOperation operation = this.messageRpc.Operations[0];
this.currentClient = this.service.GetOrCreateClient<TContract>(operation.CurrentEndpoint, this.messageRpc.Impersonating);
if (TD.RoutingServiceTransmittingMessageIsEnabled())
{
TD.RoutingServiceTransmittingMessage(this.messageRpc.EventTraceActivity, this.messageRpc.UniqueID, "0", this.currentClient.Key.ToString());
}
try
{
Message message;
if ((this.messageRpc.Transaction != null) && operation.HasAlternate)
{
throw System.ServiceModel.Routing.FxTrace.Exception.AsError(new ConfigurationErrorsException(System.ServiceModel.Routing.SR.ErrorHandlingNotSupportedReqReplyTxn(this.messageRpc.OperationContext.Channel.LocalAddress)));
}
if (operation.AlternateEndpointCount > 0)
{
message = this.messageRpc.CreateBuffer().CreateMessage();
}
else
{
message = this.messageRpc.Message;
}
operation.PrepareMessage(message);
IAsyncResult result = null;
using (base.PrepareTransactionalCall(this.messageRpc.Transaction))
{
using (IDisposable disposable = null)
{
try
{
}
finally
{
disposable = this.messageRpc.PrepareCall();
}
result = this.currentClient.BeginOperation(message, this.messageRpc.Transaction, base.PrepareAsyncCompletion(ProcessRequestAsyncResult<TContract>.operationCallback), this);
}
}
if (!base.CheckSyncContinue(result))
{
return flag;
}
if (this.OperationComplete(result))
{
base.Complete(this.allCompletedSync);
return flag;
}
return true;
}
catch (Exception exception)
{
if (Fx.IsFatal(exception))
{
throw;
}
if (!this.HandleClientOperationFailure(exception))
{
throw;
}
return true;
}
}
}
根据我的粗浅阅读,在我看来,ProcessRequestAsyncResult 正在通过 ProcessRequestAsyncResult.StartProcessing 方法执行逐步浏览备份列表的工作。然而,StartProcess() 似乎并没有抛出每个异常,而是有选择地选择是否抛出异常。
似乎只有最终死地址的异常实际上是由 StartProcess() 抛出的,然后由 RoutingService.BeginProcessRequest catch 子句传递,最后才最终使其一直到我的 IErrorHandler 实现中的激活。
这强烈表明我在这里尝试做的事情无法通过 System.ServiceModel.Routing 命名空间的当前实现来完成。请注意,RoutingService 是一个密封类,因此我无法使用自己的基类来扩展它来更改此行为,即使我认为这是一个好主意(我不这么认为)。
但话又说回来,请注意,这是一个浅阅读。我很容易就错了。事实上,我会非常喜欢被证明是错误的。我非常愿意找到一种方法让 RoutingService 完成我想要它做的事情,而不是必须自己动手。