本文整理匯總了C#中RabbitMQ.Client.MessagePatterns.Subscription類的典型用法代碼示例。如果您正苦於以下問題:C# Subscription類的具體用法?C# Subscription怎麽用?C# Subscription使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Subscription類屬於RabbitMQ.Client.MessagePatterns命名空間,在下文中一共展示了Subscription類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Main
static void Main(string[] args)
{
var factory = new ConnectionFactory
{
HostName = "localhost",
UserName = "guest",
Password = "guest",
};
var connection = factory.CreateConnection();
var channel = connection.CreateModel();
channel.QueueDeclare("LoanRequests", true, false, false, null);
var subscription = new Subscription(channel, "LoanRequests", false);
for (int i = 1; i < 10; i++)
{
var message = new LoanRequestMessage { Amount = i * 10000, Duration = i * 10, Ssn = 12312312 };
channel.BasicPublish("", "LoanRequests", null, message.ToByteArray());
Console.WriteLine("Created the following message: ");
Console.WriteLine("SSN: " + message.Ssn);
Console.WriteLine("Amount: " + message.Amount);
Console.WriteLine("Duration: " + message.Duration);
}
Environment.Exit(0);
}
示例2: Main
public static int Main(string[] args)
{
if (args.Length < 1) {
Console.Error.WriteLine("Usage: Subscriber <uri> [<message count>]");
Console.Error.WriteLine("RabbitMQ .NET client version "+typeof(IModel).Assembly.GetName().Version.ToString());
Console.Error.WriteLine("Parameters:");
Console.Error.WriteLine(" <uri> = \"amqp://user:[email protected]:port/vhost\"");
return 2;
}
string serverAddress = args[0];
long msgCount = (args.Length > 1) ? int.Parse(args[1]) : 10;
ConnectionFactory cf = new ConnectionFactory();
cf.Uri = serverAddress;
using (IConnection conn = cf.CreateConnection()) {
using (IModel ch = conn.CreateModel()) {
string queueName = ensureQueue(ch);
/* We'll consume msgCount message twice: once
using Subscription.Next() and once using the
IEnumerator interface. So, we'll send out
2*msgCount messages. */
sendMessages(ch, queueName, 2*msgCount);
using (Subscription sub = new Subscription(ch, queueName)) {
blockingReceiveMessages(sub, msgCount);
enumeratingReceiveMessages(sub, msgCount);
}
}
}
return 0;
}
示例3: RabbitMqMessageQueue
public RabbitMqMessageQueue(string connectionString, string inputQueueName)
{
this.inputQueueName = inputQueueName;
Log.Info("Opening Rabbit connection");
connection = new ConnectionFactory {Uri = connectionString}.CreateConnection();
Log.Debug("Creating model");
model = connection.CreateModel();
Log.Info("Initializing exchange and input queue");
var tempModel = connection.CreateModel();
Log.Debug("Ensuring that exchange exists with the name {0}", ExchangeName);
tempModel.ExchangeDeclare(ExchangeName, ExchangeType.Topic, true);
Log.Debug("Declaring queue {0}", this.inputQueueName);
tempModel.QueueDeclare(this.inputQueueName, true, false, false, new Hashtable());
Log.Debug("Binding {0} to {1} (routing key: {2})", this.inputQueueName, ExchangeName, this.inputQueueName);
tempModel.QueueBind(this.inputQueueName, ExchangeName, this.inputQueueName);
Log.Debug("Opening subscription");
subscription = new Subscription(model, inputQueueName);
}
示例4: Main
static void Main(string[] args)
{
var cf = new ConnectionFactory();
cf.Endpoint.HostName = "localhost";
cf.Password = "guest";
cf.UserName = "guest";
using (IConnection conn = cf.CreateConnection())
{
using (IModel ch = conn.CreateModel())
{
string queueName = ensureQueue(ch);
/* We'll consume msgCount message twice: once
using Subscription.Next() and once using the
IEnumerator interface. So, we'll send out
2*msgCount messages. */
using (var sub = new Subscription(ch, queueName))
{
blockingReceiveMessages(sub, 100);
}
}
}
return;
}
示例5: RabbitMqEventConsumer
/// <summary>
/// Initializes a new instance of the <see cref="RabbitMqEventConsumer"/> class.
/// </summary>
/// <param name="connectionFactory">The connection factory.</param>
/// <param name="exchangePath">The exchange path.</param>
/// <param name="queue">The queue.</param>
public RabbitMqEventConsumer(ConnectionFactory connectionFactory, string exchangePath, string queue)
{
_active = 1;
_connection = connectionFactory.CreateConnection();
_model = _connection.CreateModel();
_queue = _model.QueueDeclare(queue, true, false, false, new Hashtable());
// bind the queue to an exchange if specified
if (exchangePath != null)
{
_model.QueueBind(_queue, exchangePath, string.Empty);
}
EventingBasicConsumer eventingBasicConsumer = new EventingBasicConsumer();
eventingBasicConsumer.Received += HandleEvent;
_model.BasicConsume(_queue, true, eventingBasicConsumer);
#if false
_subscription = new Subscription(_model, _queue, true);
var thread = new Thread(ReceiveEvents);
thread.IsBackground = true;
thread.Name = "rabbitmq:consumer";
thread.Start();
#endif
var uriBuilder = new UriBuilder(
"rabbitmq",
connectionFactory.HostName,
connectionFactory.Port,
queue);
Uri = uriBuilder.Uri;
}
示例6: ProcessMessages
public void ProcessMessages()
{
using (_connection = _factory.CreateConnection())
{
using (var channel = _connection.CreateModel())
{
Console.WriteLine("Listening for Topic <payment.purchaseorder>");
Console.WriteLine("------------------------------------------");
Console.WriteLine();
channel.ExchangeDeclare(ExchangeName, "topic");
channel.QueueDeclare(PurchaseOrderQueueName, true, false, false, null);
channel.QueueBind(PurchaseOrderQueueName, ExchangeName, "payment.purchaseorder");
channel.BasicQos(0, 10, false);
Subscription subscription = new Subscription(channel, PurchaseOrderQueueName, false);
while (true)
{
BasicDeliverEventArgs deliveryArguments = subscription.Next();
var message = (PurchaseOrder)deliveryArguments.Body.DeSerialize(typeof(PurchaseOrder));
var routingKey = deliveryArguments.RoutingKey;
Console.WriteLine("-- Purchase Order - Routing Key <{0}> : {1}, £{2}, {3}, {4}", routingKey, message.CompanyName, message.AmountToPay, message.PaymentDayTerms, message.PoNumber);
subscription.Ack(deliveryArguments);
}
}
}
}
示例7: ProcessMessages
public void ProcessMessages()
{
using (_connection = _factory.CreateConnection())
{
using (var channel = _connection.CreateModel())
{
Console.WriteLine("Listening for Topic <payment.*>");
Console.WriteLine("------------------------------");
Console.WriteLine();
channel.ExchangeDeclare(ExchangeName, "topic");
channel.QueueDeclare(AllQueueName, true, false, false, null);
channel.QueueBind(AllQueueName, ExchangeName, "payment.*");
channel.BasicQos(0, 10, false);
Subscription subscription = new Subscription(channel, AllQueueName, false);
while (true)
{
BasicDeliverEventArgs deliveryArguments = subscription.Next();
var message = deliveryArguments.Body.DeSerializeText();
Console.WriteLine("Message Received '{0}'", message);
subscription.Ack(deliveryArguments);
}
}
}
}
示例8: Subscribe
public void Subscribe(string queueName, Action<string> callback)
{
this.Subscriptions = this.Subscriptions ?? Enumerable.Empty<Task>();
this.Subscriptions = this.Subscriptions.Concat(new[] {
Task.Factory.StartNew(delegate {
var factory = new ConnectionFactory()
{
VirtualHost = "/",
HostName = "127.0.0.1",
Port = AmqpTcpEndpoint.UseDefaultPort
};
factory.UserName = "guest";
factory.Password = "guest";
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
var subscription = new Subscription(channel, queueName, false);
while(true)
{
var eventArgs = subscription.Next();
var content = eventArgs == null ? string.Empty : Encoding.UTF8.GetString(eventArgs.Body);
subscription.Ack(eventArgs);
callback(content);
}
}
}
}
)});
}
示例9: Subscribe
public void Subscribe(string queueName)
{
ch.QueueBind(queueName, "amq.direct", queueName, false, null);
using (Subscription sub = new Subscription(ch, queueName))
{
ReceiveMessages(sub);
}
}
示例10: StartListening
public void StartListening(Action<byte[], IDictionary<string, object>> onMessage)
{
if (this.IsListening)
throw new InvalidOperationException("Client is already listening for messages");
Action subscribeAction =
() =>
{
try
{
subscriptionLifetimeResetEvent.Reset();
Subscription subscriptionHandler = new Subscription(this.Connection.GetModel(), this.QueueName);
int waitForMessagesTimeout = 100;
this.loopControlResetEvent.Reset();
while (!loopControlResetEvent.IsSet)
{
try
{
BasicDeliverEventArgs delivery = null;
if (subscriptionHandler.Next(waitForMessagesTimeout, out delivery))
{
if (delivery == null)
continue;
// Deliver message
var p = CreateProperties(delivery);
onMessage(delivery.Body, p);
}
}
catch (ThreadAbortException)
{
// Nothing to do, thread is being aborted.
// Set the reset event to leave gracefully
loopControlResetEvent.Set();
}
catch (Exception)
{
// Any other exception should be ignored.
}
}
// Close the subscription if its still open
if (subscriptionHandler.Model.IsOpen)
{
subscriptionHandler.Close();
}
}
finally
{
subscriptionLifetimeResetEvent.Set();
}
};
this.currentSubscription = subscribeAction;
}
示例11: TestSequentialIterationWithDrainer
protected void TestSequentialIterationWithDrainer(Action<Subscription> action)
{
IDictionary<string, object> args = new Dictionary<string, object>
{
{Headers.XMessageTTL, 5000}
};
string queueDeclare = Model.QueueDeclare("", false, true, false, args);
var subscription = new Subscription(Model, queueDeclare, false);
PreparedQueue(queueDeclare);
var drainer = new SubscriptionDrainer(subscription, action);
drainer.Drain();
}
示例12: OneConsumer
private int OneConsumer()
{
using (var connection = Helpers.CreateConnectionToSecondaryVirtualHostOnAlternativePort())
using (var model = connection.CreateModel())
{
var queue = model.QueueDeclare();
model.QueueBind(queue, Constants.FederationExchangeName, "#");
var subscription = new Subscription(model, queue, true);
consumerReady.Set();
return subscription.Next().Body.Integer();
}
}
示例13: TestConsumerCancellationNotification
public void TestConsumerCancellationNotification()
{
var q = Guid.NewGuid().ToString();
this.Model.QueueDeclare(queue: q, durable: false, exclusive: false, autoDelete: false, arguments: null);
var sub = new Subscription(this.Model, q);
var latch = new ManualResetEvent(false);
sub.Consumer.ConsumerCancelled += (_sender, _args) =>
{
sub.Close();
latch.Set();
Conn.Close();
};
this.Model.QueueDelete(q);
Wait(latch, TimeSpan.FromSeconds(4));
}
示例14: blockingReceiveMessages
private static void blockingReceiveMessages(Subscription sub, long msgCount)
{
Console.WriteLine("Receiving {0} messages (using a Subscriber)", msgCount);
for (int i = 0; i < msgCount; ++i)
{
Console.WriteLine("Message {0}: {1} (via Subscription.Next())",
i, messageText(sub.Next()));
Console.WriteLine("Message {0} again: {1} (via Subscription.LatestEvent)",
i, messageText(sub.LatestEvent));
sub.Ack();
}
Console.WriteLine("Done.\n");
}
示例15: RunConsumer
private void RunConsumer(
string queueName)
{
new Task(() =>
{
var _channel = this.c_connection.CreateModel();
var _consumer = new Subscription(_channel, queueName);
foreach (BasicDeliverEventArgs _messageDelivery in _consumer)
{
this.c_writeLog(string.Format("Received message on q {0}, tag = {1}", queueName, _messageDelivery.DeliveryTag));
_consumer.Ack(_messageDelivery);
}
}).Start();
}