Example #1
0
        protected override Consumer InstantiateConsumer(IEndpoint endpoint)
        {
            var consumer = new TestConsumer(this, endpoint);

            Consumers.Add(consumer);
            return(consumer);
        }
Example #2
0
        /// <summary>
        /// Opens the specified connection.
        /// </summary>
        /// <param name="connection">The connection.</param>
        public void Open(Connection connection)
        {
            _logger.InfoFormat("Dispatcher: Opening connection {0}", connection.Name);

            AddConnectionToConnections(connection);
            var addedConsumers = CreateConsumers(new[] { connection });

            switch (State)
            {
            case DispatcherState.DS_RUNNING:
                addedConsumers.Each(
                    (consumer) =>
                {
                    Consumers.Add(consumer);
                    consumer.Open();
                    _tasks.Add(consumer.Job);
                });
                break;

            case DispatcherState.DS_STOPPED:
            case DispatcherState.DS_AWAITING:
                addedConsumers.Each((consumer) => Consumers.Add(consumer));
                Start();
                break;

            default:
                throw new InvalidOperationException("The dispatcher is not ready");
            }
        }
Example #3
0
 /// <summary>
 /// Add a consumer as a transient instance. It must inherit from IConsumer&lt;T&gt; where T is the message you want to respond ot.
 /// </summary>
 /// <typeparam name="T">The type of the consumer to add.</typeparam>
 public void AddTransientConsumer <T>() where T : class, IConsumer
 {
     Consumers.Add(new MassTransitServiceRegistration()
     {
         Type     = typeof(T),
         Lifetime = Lifetime.Transient
     });
 }
Example #4
0
        public void AddConsumer(string name, IMessagingSettings queueSettings)
        {
            if (!Consumers.ContainsKey(name))
            {
                var consumer = this.CreateConsumer(queueSettings);
                Consumers.Add(name, consumer);
            }

            Consumers[name].StartListeningMessages();
        }
Example #5
0
        ///<summary>
        ///Adds another ProducerConsumer to the list of processing consumers.
        ///<para>This method will throw a CycleException if a consumer would be tasked to be its own producer.</para>
        ///</summary>
        public void AddConsumer(GhostLine <T> consumer)
        {
            if (AncestorDuplicate(consumer) || DescendantDuplicate(consumer))
            {
                throw new CycleException("Adding this consumer would create a cycle.");
            }

            consumer.Parent = this;
            Consumers.Add(consumer);
        }
Example #6
0
        public MockBuilder(string connectionString, Action <IServiceRegister> registerServices)
        {
            for (int i = 0; i < 10; i++)
            {
                channelPool.Push(Substitute.For <IModel>());
            }

            ConnectionFactory.CreateConnection().Returns(Connection);
            ConnectionFactory.Next().Returns(false);
            ConnectionFactory.Succeeded.Returns(true);
            ConnectionFactory.CurrentHost.Returns(new HostConfiguration
            {
                Host = Host,
                Port = PortNumber
            });
            ConnectionFactory.Configuration.Returns(new ConnectionConfiguration
            {
                VirtualHost = VirtualHost,
            });

            Connection.IsOpen.Returns(true);

            Connection.CreateModel().Returns(i =>
            {
                var channel = channelPool.Pop();
                Channels.Add(channel);
                channel.CreateBasicProperties().Returns(BasicProperties);
                channel.IsOpen.Returns(true);
                channel.BasicConsume(null, false, null, true, false, null, null)
                .ReturnsForAnyArgs(consumeInvokation =>
                {
                    var queueName   = (string)consumeInvokation[0];
                    var consumerTag = (string)consumeInvokation[2];
                    var consumer    = (IBasicConsumer)consumeInvokation[6];

                    ConsumerQueueNames.Add(queueName);
                    consumer.HandleBasicConsumeOk(consumerTag);
                    Consumers.Add(consumer);
                    return(string.Empty);
                });

                return(channel);
            });

            Bus = RabbitHutch.CreateBus(connectionString, x =>
            {
                registerServices(x);
                x.Register(_ => ConnectionFactory);
                x.Register(_ => Logger);
            });

            Assert.NotNull(Bus);
            Assert.NotNull(Bus.Advanced);
            Assert.NotNull(Bus.Advanced.Container);
        }
        public virtual void MergeFrom(MessageBusSettings settings)
        {
            if (settings is null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (settings.Producers.Count > 0)
            {
                foreach (var p in settings.Producers)
                {
                    Producers.Add(p);
                }
            }

            if (settings.Consumers.Count > 0)
            {
                foreach (var c in settings.Consumers)
                {
                    Consumers.Add(c);
                }
            }

            if (Serializer == null && settings.Serializer != null)
            {
                Serializer = settings.Serializer;
            }

            if (RequestResponse == null && settings.RequestResponse != null)
            {
                RequestResponse = settings.RequestResponse;
            }

            if (Serializer == null && settings.Serializer != null)
            {
                Serializer = settings.Serializer;
            }

            if (DependencyResolver == null && settings.DependencyResolver != null)
            {
                DependencyResolver = settings.DependencyResolver;
            }

            if (OnMessageExpired == null && settings.OnMessageExpired != null)
            {
                OnMessageExpired = settings.OnMessageExpired;
            }

            if (OnMessageFault == null && settings.OnMessageFault != null)
            {
                OnMessageFault = settings.OnMessageFault;
            }
        }
Example #8
0
        /// <summary>
        /// Inherited class must call this initializer method first.
        /// </summary>
        /// <param name="name">The name of the <see cref="AsyncQueue"/></param>
        /// <param name="asyncQueue">The <see cref="IAsyncQueue"/> implementation</param>
        /// <param name="consumerCount">Number of consumers</param>
        /// <param name="priority">priority of consumer threads</param>
        protected void Initialize(
            string name,
            IAsyncQueue asyncQueue,
            int consumerCount,
            ThreadPriority priority)
        {
            Assert.IsTrue(consumerCount > 0);

            _name       = name;
            _asyncQueue = asyncQueue;

            for (var id = 0; id < consumerCount; id++)
            {
                var consumerThread = new ConsumerThread(this, id, priority);
                Consumers.Add(consumerThread.Thread);
            }
        }
Example #9
0
 /// <summary>
 /// Opens the specified connection.
 /// </summary>
 /// <param name="connection">The connection.</param>
 /// <exception cref="System.InvalidOperationException">Use Recieve to start the dispatcher; use Open to start a shut or added connection</exception>
 public void Open(Connection connection)
 {
     if (State == DispatcherState.DS_RUNNING)
     {
         logger.Debug(m => m("Dispatcher: Opening connection {0}", connection.Name));
         var addedConsumers = CreateConsumers(new List <Connection>()
         {
             connection
         });
         addedConsumers.Each((consumer) =>
         {
             Consumers.Add(consumer);
             consumer.Open();
             tasks.Add(consumer.Job);
         });
     }
     else
     {
         throw new InvalidOperationException("Use Recieve to start the dispatcher; use Open to start a shut or added connection");
     }
 }
Example #10
0
        /// <summary>
        /// 根据配置创建消费者
        /// </summary>
        /// <param name="itemKey"></param>
        private void RunFactory(MqConsumerItemKey itemKey)
        {
            //pull 方式消费消息
            var configModel = TaskList.First(t => t.Exchange == itemKey.Exchange && t.RoutingKey == itemKey.RoutingKey && t.QueueName == itemKey.QueueName);

            if (configModel.MqMessageType == 0)
            {
                Thread th = new Thread(() => ParameterizedThreadStart(itemKey));
                th.Name         = string.Format("{0}-{1}-{2}", itemKey.Exchange, itemKey.RoutingKey, itemKey.QueueName);
                th.IsBackground = true;
                threadList.Add(th);
            }
            //sub 方式消费消息
            else
            {
                var consumer = QueueFactory <IConsumer> .Create();

                consumer.Subscribe(itemKey.Exchange, itemKey.QueueName, itemKey.RoutingKey, configModel.IsProperties, MqMessageExecute, false);
                Consumers.Add(consumer);
            }
        }
Example #11
0
        public ConsumerCollection AddConsumersInheritingFrom <TConsumer>(Assembly[] assembliesToScan) where TConsumer : IConsumer
        {
            if (!assembliesToScan.Any())
            {
                throw new ArgumentException("At least one assembly must be provided!");
            }

            var consumerBaseType = typeof(TConsumer);

            EnsureAssembliesScanned(assembliesToScan);

            foreach (var assembly in assembliesToScan)
            {
                var assemblyConsumers = AssemblyConsumers[assembly.FullName];
                foreach (var eligibleConsumer in assemblyConsumers.Where(t => consumerBaseType.IsAssignableFrom(t)))
                {
                    Consumers.Add(eligibleConsumer);
                }
            }

            return(this);
        }
Example #12
0
        public virtual IMessageProvider Register(MessageKind[] kinds)
        {
            if (kinds == null || kinds.Length < 1)
            {
                throw new ArgumentNullException("kinds");
            }
            kinds = kinds.Distinct().OrderBy(e => e).ToArray();
            if (kinds == null || kinds.Length < 1)
            {
                throw new ArgumentNullException("kinds");
            }

            // 检查注册范围是否有效
            var ks = Kinds;

            if (ks != null)
            {
                foreach (var item in kinds)
                {
                    if (Array.IndexOf <MessageKind>(ks, item) < 0)
                    {
                        throw new ArgumentOutOfRangeException("kinds", "当前消息提供者不支持Kind=" + item + "的消息!");
                    }
                }
            }

            var mc = new MessageConsumer()
            {
                Parent = this, Kinds = kinds
            };

            lock (Consumers)
            {
                Consumers.Add(mc);
            }
            mc.OnDisposed += (s, e) => Consumers.Remove(s as MessageConsumer);
            return(mc);
        }
Example #13
0
        /// <summary>
        /// Given an array of events, this method creates new consumer types from a generic base type
        /// by replacing the generic parameter with the given event types.
        /// </summary>
        public ConsumerCollection AddGenericConsumersFromEvents(Type genericConsumerType, params Type[] eventTypes)
        {
            // Verify that the genericConsumerType is indeed a generic type. Moreover,
            // it should have only one generic parameter, and be assignable to IConsumer
            if (!typeof(IConsumer).IsAssignableFrom(genericConsumerType))
            {
                throw new ArgumentException($"Consumer type must implement {nameof(IConsumer)}");
            }

            if (!genericConsumerType.IsGenericType || genericConsumerType.GetGenericArguments().Length != 1)
            {
                throw new ArgumentException(
                          "Consumer type should be generic and accept only a single generic argument.");
            }

            foreach (var eventType in eventTypes)
            {
                var consumerType = genericConsumerType.MakeGenericType(eventType);
                Consumers.Add(consumerType);
            }

            return(this);
        }
        /// <summary>
        /// Writes the functions.
        /// </summary>
        /// <param name="funcs">The funcs.</param>
        /// <returns></returns>
        private static List <string> WriteFunctions(List <Models.Function> funcs)
        {
            List <string> _funcs = new List <string>();

            funcs.ForEach((n) =>
            {
                string inputs = string.Empty;
                if (!Core.BaseTypes.Contains(n.Return))
                {
                    Providers.Add(n.Return.Replace("[]", ""));
                }
                n.Inputs.ForEach((x) =>
                {
                    if ((!Core.DataTypes.Contains(x.Type)) && (!Core.BaseTypes.Contains(Regex.Replace(x.Type.Name, Reflector.TypingSetter, ""))))
                    {
                        Consumers.Add(Regex.Replace(x.Type.Name, Reflector.TypingSetter, ""));
                    }
                    inputs += (string.Format(Overload_Notation, x.Name, Regex.Replace(x.Type.Name, Reflector.TypingSetter, "[]")) + ",");
                });
                _funcs.Add('\t' + string.Format(Method_Notation, "+", n.Name, ((inputs.Length > 0) ? inputs.TrimEnd(',') : ""), n.Return.Replace("[]", "")));
            });

            return(_funcs);
        }
Example #15
0
        private void ParameterizedThreadStart(MqConsumerItemKey mqItemKey)
        {
            var configModel = TaskList.FirstOrDefault(t => t.Exchange == mqItemKey.Exchange && t.RoutingKey == mqItemKey.RoutingKey && t.QueueName == mqItemKey.QueueName);

            //创建一个消费者
            if (configModel.IsNull())
            {
                //记录日志
                LogHelper.LogInfo(logSource, string.Format("ParameterizedThreadStart 配置PULL方式消费者未找到业务配置: {0};{1};{2}", mqItemKey.Exchange, mqItemKey.RoutingKey, mqItemKey.QueueName));
                return;
            }
            var Consumer = QueueFactory <IConsumer> .Create();

            Consumers.Add(Consumer);
            if (configModel.MqMessageType == 0)
            {
                do
                {
                    Consumer.Pull(mqItemKey.Exchange, mqItemKey.QueueName, mqItemKey.RoutingKey, MqMessageExecute);
                    var timeInterval = configModel.TimeInterval == 0 ? 10 : configModel.TimeInterval;
                    Thread.CurrentThread.Join(timeInterval);
                }while (true);
            }
        }
Example #16
0
        public ConsumerCollection AddConsumer <TConsumer>() where TConsumer : IConsumer
        {
            Consumers.Add(typeof(TConsumer));

            return(this);
        }
Example #17
0
 /// <summary>
 /// Begins listening for messages on channels, and dispatching them to request handlers.
 /// </summary>
 public void Receive()
 {
     CreateConsumers(Connections).Each(consumer => Consumers.Add(consumer));
     Start();
 }
Example #18
0
 public void AddConsumer(Neuron neuron)
 {
     Consumers.Add(neuron);
 }
Example #19
0
 public void AddConsumer(Consumer consumer)
 {
     Consumers.Add(consumer);
 }
Example #20
0
 public void Subscribe(ConsumerSetup setup)
 {
     Consumers.Add(setup);
 }