/// <summary> /// Receive messages from message queue. /// This method will register the given function to consume queue. /// </summary> /// <param name="name">Name of queue or whatever using to describing work/job/event. Same as Send method's name.</param> /// <param name="func">Receiver function.</param> /// <returns>Returns true if receiver method registered successfully, otherwise returns false.</returns> /// <exception cref="Exception">Throws when name or func is null.</exception>> public bool Receive(string name, Func <string, bool> func) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } if (func == null) { throw new ArgumentNullException(nameof(func)); } // Get new channel. var channel = _channelFactory.Channel; // Create queue if it is not exist. var queueName = name; channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); // Create new consumer. var consumer = _eventingBasicConsumerImpl.GetEventingBasicConsumer(channel); // Register to job received event. consumer.Received += (model, ea) => { _consumerInvoker.Invoke(func, ea, channel); }; // Start consuming. channel.BasicConsume(queueName, autoAck: false, consumer: consumer); return(true); }
public void Publish <T>(T message) where T : class { var descriptors = _registry.GetConsumers(message); if (!descriptors.Any()) { return; } var envelopeType = typeof(ConsumeContext <>).MakeGenericType(typeof(T)); var envelope = (ConsumeContext <T>)FastActivator.CreateInstance(envelopeType, message); foreach (var descriptor in descriptors) { var consumer = _resolver.Resolve(descriptor); if (consumer != null) { _invoker.Invoke(descriptor, consumer, envelope); } } }