【问题标题】:WCF right solution for Publish/subscribe pattern implementation发布/订阅模式实现的 WCF 正确解决方案
【发布时间】:2011-09-15 12:53:22
【问题描述】:

我用 WCF 和 WSDualHttpBinding 实现了我自己的发布/订阅模式实现代码,但是我对稍后解释的超时有点问题,现在让我展示一下我在做什么:

public interface IEventSubscriber
{
    [OperationContract]
    void NotifyEvent(EventNotification notification);
    [OperationContract]
    void NotifyServiceDisconnecting();
}

[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IEventSubscriber))]
public interface IEventPublisherService
{
    [OperationContract(IsOneWay = false, IsInitiating = true)]
    void Subscribe(string culture);
    [OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = true)]
    void Unsubscribe();
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
internal class EventPublisherServiceImpl : IEventPublisherService
{
    ServiceHost host;
    public bool StartService()
    {
        bool ret = false;
        try
        {
            Uri baseAddress = new Uri(ConfigurationManager.AppSettings[GlobalConstants.CfgKeyConfigEventPublishserServiceBaseAddress].ToString());
            EventHelper.AddEvent(string.Format("Event Publisher Service on: {0}", baseAddress.ToString()));

            host = new ServiceHost(this, baseAddress);

            // duplex session enable http binding
            WSDualHttpBinding httpBinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
            httpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            httpBinding.ReliableSession = new ReliableSession();
            httpBinding.ReliableSession.Ordered = true;
            httpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
            host.AddServiceEndpoint(typeof(IEventPublisherService), httpBinding, baseAddress);

            // Enable metadata publishing.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            // Open the ServiceHost to start listening for messages.
            host.Open();
            ret = true;
        }
        catch (Exception e)
        {
            EventHelper.AddException(e.Message);
        }

        return ret;
    }
 ...

}

现在在我的实现类中,我有一个存储在内存中的订阅者列表,当收到新通知时,将为每个订阅者执行以下代码:

 ...
    /// <summary>
    /// List of active subscribers
    /// </summary>
    private static Dictionary<IEventSubscriber, string> subscribers = new Dictionary<IEventSubscriber, string>();

 ...

我是这样使用它的:

    internal void Subscribe(string culture)
    {
        lock (subscribers)
        {
            // Get callback contract as specified on the service definition
            IEventSubscriber callback = OperationContext.Current.GetCallbackChannel<IEventSubscriber>();

            // Add subscriber to the list of active subscribers
            if (!subscribers.ContainsKey(callback))
            {
                subscribers.Add(callback, culture);
            }
        }
    }

 ...

    private void OnNotificationEvent(NormalEvent notification)
    {
        lock (subscribers)
        {
            List<IEventSubscriber> listToRemove = new List<IEventSubscriber>();
            //  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
            Parallel.ForEach(subscribers, kvp =>
            {
                try
                {
                    kvp.Key.NotifyEvent(new EventNotification(notification, kvp.Value));
                }
                catch (Exception ex)
                {
                    EventHelper.AddException(string.Format("Error notifying event notification to client: {0} - removing this one", ex.Message));
                    listToRemove.Add(kvp.Key);
                }

            } //close lambda expression
            ); //close method invocation

            Parallel.ForEach(listToRemove, subs =>
            {
                try
                {
                    subs.NotifyServiceDisconnecting();
                }
                catch (Exception ex) {
                    EventHelper.AddException(string.Format("Failed to notify client that is to be removed: {0}", 
                        ex.Message));
                }
                subscribers.Remove(subs);
            }
            );
        }
    }

这有什么问题,当超时(请注意,我为 ReceiveTimeout 和非活动超时设置了 10 分钟)列表中的订阅者进入故障状态,并且在 中捕获了以下异常OnNotificationEvent

*操作“NotifyEvent”无法完成,因为会话通道超时等待接收消息。要增加超时,请在配置文件中的绑定上设置 receiveTimeout 属性,或直接在 Binding 上设置 ReceiveTimeout 属性。 *

好的,我可以增加超时值,但如果我这样做,它最终会发生一段时间。

我的问题是:我在尝试实现这种模式时做错了什么?还是存在任何其他方式来实现此模式以更好地避免此问题?或存在重新连接故障回调通道的任何方式(对于我正在阅读的内容,这是不可能的,但由于我无法通知客户端连接丢失,让客户端盲目不知道通信结束!?或者是一种让他知道他与出版商失去联系的方式!?)

当然,像 ping 消息这样的解决方案已经过时了 :) 但是好的,如果没有更好的出现,我必须实现类似的东西......

谢谢

【问题讨论】:

    标签: c# wcf


    【解决方案1】:

    目前的解决方案是将超时更改为无限值:

                // duplex session enable http binding
                WSDualHttpBinding httpBinding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
                httpBinding.ReceiveTimeout = TimeSpan.MaxValue;
                httpBinding.ReliableSession = new ReliableSession();
                httpBinding.ReliableSession.Ordered = true;
                httpBinding.ReliableSession.InactivityTimeout = TimeSpan.MaxValue;
    

    【讨论】:

      【解决方案2】:

      您正在使用 Parallel.ForEach,但我不确定这是否足够。 AFAIR Parallel.ForEach 不会在单独的线程中执行每次迭代。

      我想建议在 OnNotificationEvent 中为每个订阅者启动单独的线程,并使用 lock 来确保 foreach 不会被 Collection 修改异常破坏:

      lock (_subscribersSync)
               foreach (var chatter in subscribers)
               {
                       Logger.Log.DebugFormat("putting all users to {0}", subscribers.Key.Name);
                       Thread th = new Thread(PublishAllUserMessage);
                       th.Start(new MessageData() { Message = "", Subscriber = chatter.Key};
               }
      
      void PublishAllUserMessage(object messageData)
      {
              MessageData md = (MessageData)messageData;
              try
              {
                      md.Subscriber.NotifyEvent(...event parameters here ...);
              }
              catch (Exception ex)
              {
                      Logger.Log.Error(string.Format("failed to publish message to '{0}'", md.Subscriber.Name), ex);
                      KickOff(md.Subscriber);
              }
      }
      object _subscribersSync = new object();
      void KickOff(IEventSubscriber p)
      {
              lock (_subscribersSync)
              {
                      subscribers.Remove(p);
                      Logger.Log.WarnFormat("'{0}' kicked off", p.Name);
              }
      }
       public class MessageData
       {
               public string Message;
               public IEventSubscriber Subscriber;
      }
      

      【讨论】:

      • 好的,但是 paralel.ForEach 和你对线程做的一样,或者类似的,如果我有 2000 个我不想要的客户,它不会创建所有线程做得更好启动 2000 个线程我是对还是错?
      • AFAIR 不能保证 Paralel.ForEach 在单独的线程中执行每次迭代。是的,它看起来并不难看,但我已经展示了工作系统中的一部分代码。您可以使用 ThreadPool 而不是创建 Thread 对象。只需尝试在单独的线程中调用订阅者 NotifyEvent 并测试它对 2k 元素的工作方式。我想超时会消失。另外我想说这是跨进程调用,您应该记住,2k 订阅者的大量事件可能会导致您的网络因 Paralel.ForEach 或 Threads 而过载。
      • 但是我指向的超时是 ReceiveTimeout 和 InactivityTimeout 不是执行超时,但是好的我会尝试用线程来做这个
      猜你喜欢
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多