本文整理汇总了C#中IModel.BasicAck方法的典型用法代码示例。如果您正苦于以下问题:C# IModel.BasicAck方法的具体用法?C# IModel.BasicAck怎么用?C# IModel.BasicAck使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IModel
的用法示例。
在下文中一共展示了IModel.BasicAck方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: StartListening
public override void StartListening()
{
_rabbitConnection = Configuration.ConnectionFactory.CreateConnection();
_publishModel = _rabbitConnection.CreateModel();
_subscribeModel = _rabbitConnection.CreateModel();
_publishModel.ExchangeDeclare(Configuration.StampExchangeName, "x-stamp", durable: true);
_subscribeModel.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout, durable: true);
_subscribeModel.QueueDeclare(Configuration.QueueName, durable: false, exclusive: false, autoDelete: true, arguments: new Dictionary<string, object>());
_subscribeModel.QueueBind(Configuration.QueueName, Configuration.ExchangeName, "");
var consumer = new EventingBasicConsumer(_subscribeModel);
consumer.Received += (sender, args) =>
{
try
{
OnMessage(new RabbitMqMessageWrapper
{
Bytes = args.Body,
Id = Convert.ToUInt64(args.BasicProperties.Headers["stamp"])
});
}
finally
{
_subscribeModel.BasicAck(args.DeliveryTag, multiple: false);
}
};
_subscribeModel.BasicConsume(Configuration.QueueName, noAck: false, consumer: consumer);
}
示例2: ReceiveDotNetObjects
private static void ReceiveDotNetObjects(IModel model)
{
model.BasicQos(0, 1, false);
QueueingBasicConsumer consumer = new QueueingBasicConsumer(model);
model.BasicConsume(CommonService.DotNetObjectQueueName, false, consumer);
while (true)
{
BasicDeliverEventArgs deliveryArguments = consumer.Queue.Dequeue() as BasicDeliverEventArgs;
string objectType = deliveryArguments.BasicProperties.Type;
Type t = Type.GetType(objectType);
String jsonified = Encoding.UTF8.GetString(deliveryArguments.Body);
object rawObject = JsonConvert.DeserializeObject(jsonified, t);
Console.WriteLine("Object type: {0}", objectType);
if (rawObject.GetType() == typeof(Customer))
{
Customer customer = rawObject as Customer;
Console.WriteLine("Customer name: {0}", customer.Name);
}
else if (rawObject.GetType() == typeof(NewCustomer))
{
NewCustomer newCustomer = rawObject as NewCustomer;
Console.WriteLine("NewCustomer name: {0}", newCustomer.Name);
}
model.BasicAck(deliveryArguments.DeliveryTag, false);
}
}
示例3: Process
public void Process(
IModel channel,
BasicDeliverEventArgs message)
{
var _logMessageContext = string.Format("type header = {0}, message Id = {1}, correlation Id = {2} and delivery tag = {3}",
message.BasicProperties.Type,
message.BasicProperties.MessageId,
message.BasicProperties.CorrelationId,
message.DeliveryTag);
this.c_logger.DebugFormat("Process About to handle message, {0}", _logMessageContext);
if (!this.c_configuration.MessageConsumers.HasConfiguration(message.BasicProperties.Type))
{
this.c_logger.DebugFormat("Process No match found for message, {0}", _logMessageContext);
//pending - see errored below
channel.BasicNack(message.DeliveryTag, false, false);
return;
}
var _configuration = this.c_configuration.MessageConsumers[message.BasicProperties.Type];
var _actionResult = ConsumerHandlerResult.None;
try
{
this.c_logger.DebugFormat("Process About to deserialze message for message, {0}", _logMessageContext);
var _messageJson = Encoding.UTF8.GetString(message.Body);
var _message = JsonConvert.DeserializeObject(_messageJson, _configuration.Type);
this.c_logger.DebugFormat("Process About to invoke action for message, {0}", _logMessageContext);
_actionResult = _configuration.Action(_message as Message);
}
catch (Exception exception)
{
this.c_logger.WarnFormat("Process Encountered error for message {0} Error: {1}", _logMessageContext, exception.InstrumentationString());
_actionResult = ConsumerHandlerResult.Errored;
}
this.c_logger.DebugFormat("Process Completed processing for message, {0}, result is {1}", _logMessageContext, _actionResult);
if (_actionResult == ConsumerHandlerResult.Errored)
{
//pending - should i use configuration properties
// Nack, do not requeue, dead letter the message if dead letter exchange configured for the queue
channel.BasicNack(message.DeliveryTag, false, false);
}
else if (_actionResult == ConsumerHandlerResult.Completed)
{
channel.BasicAck(message.DeliveryTag, false);
}
else if (_actionResult == ConsumerHandlerResult.Requeue)
{
//pending does this make sense ?
channel.BasicReject(message.DeliveryTag, true);
}
this.c_logger.DebugFormat("Process Completed handling message, {0}, Result is {1}", _logMessageContext, _actionResult);
}
示例4: Exec
// ReSharper disable ConditionIsAlwaysTrueOrFalse
public static void Exec(bool durable, bool ack, IModel model, IConnection connection)
{
var queueName = "CSharpPublish" + (durable ? "Durable" : "NotDurable");
if (!string.IsNullOrWhiteSpace(_overrideQueueName))
queueName = _overrideQueueName;
Console.WriteLine("Durability {0} enabled", durable ? "IS" : "is NOT");
Console.WriteLine("ACK {0} enabled", ack ? "IS" : "is NOT");
Console.WriteLine("Creating queue {0}...", queueName);
model.QueueDeclare(queueName, durable, false, false, null);
var msg = Encoding.UTF8.GetBytes("Hello from my PC !");
var properties = new BasicProperties { DeliveryMode = (byte)(durable ? 2 : 1) };
if (_publish)
{
for (int i = 0; i < _numMsgs; i++)
model.BasicPublish(string.Empty, queueName, properties, msg);
Console.WriteLine("Published!");
}
uint msgs = 0;
if (_receive)
{
Console.WriteLine("Reading...");
var fromMac = false;
while (connection.IsOpen)
{
var result = model.BasicGet(queueName, ack == false);
if (result == null)
break;
if (msgs % 3144 == 0)
Console.WriteLine(msgs);
if (ack)
model.BasicAck(result.DeliveryTag, false);
var msgText = Encoding.UTF8.GetString(result.Body);
if (msgText.Contains("Mac"))
fromMac = true;
msgs++;
}
if (fromMac)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Received messages from the mac");
Console.ResetColor();
}
}
}
示例5: ProcessMessage
private void ProcessMessage(IModel channel, EventingBasicConsumer consumer)
{
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
var processor = new SimpleProcess();
processor.DoProcess(message);
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
}
示例6: AckOrReject
private static void AckOrReject(IModel channel, ulong deliveryTag, string message)
{
if (message.Contains("WTF"))
{
Console.WriteLine("REJECTED: {0}", message);
channel.BasicReject(deliveryTag, false);
}
else
{
Console.WriteLine("Received: {0}", message);
channel.BasicAck(deliveryTag, false);
}
}
示例7: ReceiveBufferedMessages
private static void ReceiveBufferedMessages(IModel model)
{
model.BasicQos(0, 1, false);
QueueingBasicConsumer consumer = new QueueingBasicConsumer(model);
model.BasicConsume(RabbitMqService.LargeMessageBufferedQueue, false, consumer);
while (true)
{
BasicDeliverEventArgs deliveryArguments = consumer.Queue.Dequeue() as BasicDeliverEventArgs;
byte[] messageContents = deliveryArguments.Body;
string randomFileName = string.Concat(@"c:\large_file_from_rabbit_", Guid.NewGuid(), ".txt");
Console.WriteLine("Received message, will save it to {0}", randomFileName);
File.WriteAllBytes(randomFileName, messageContents);
model.BasicAck(deliveryArguments.DeliveryTag, false);
}
}
示例8: BasicAck
protected void BasicAck(IModel channel, BasicDeliverEventArgs args)
{
try
{
_logger.LogDebug($"Ack:ing message with id {args.DeliveryTag}.");
channel.BasicAck(
deliveryTag: args.DeliveryTag,
multiple: false
);
}
catch (AlreadyClosedException)
{
_logger.LogWarning("Unable to ack message, channel is allready closed.");
_processedButNotAcked.Add(args.BasicProperties.MessageId);
}
}
示例9: DemoQueue
// This shows handling messages from a queue - each message is handled by a single worker
static void DemoQueue(IModel model)
{
model.QueueDeclare("myqueue", true, false, false, null);
model.BasicQos(0, 1, false);
var consumer = new QueueingBasicConsumer(model);
model.BasicConsume("myqueue", false, consumer);
while (true)
{
var message = consumer.Queue.Dequeue();
DoWork(message);
// Since BasicConsume is called with noAck: false, we need to manually let Rabbit know that the message was handled
model.BasicAck(message.DeliveryTag, false);
}
}
示例10: ReceiveSerialisationMessages
private static void ReceiveSerialisationMessages(IModel model)
{
model.BasicQos(0, 1, false);
QueueingBasicConsumer consumer = new QueueingBasicConsumer(model);
model.BasicConsume(CommonService.SerialisationQueueName, false, consumer);
while (true)
{
BasicDeliverEventArgs deliveryArguments = consumer.Queue.Dequeue() as BasicDeliverEventArgs;
string contentType = deliveryArguments.BasicProperties.ContentType;
string objectType = deliveryArguments.BasicProperties.Type;
String jsonified = Encoding.UTF8.GetString(deliveryArguments.Body);
Customer customer = JsonConvert.DeserializeObject<Customer>(jsonified);
Console.WriteLine("Pure json: {0}", jsonified);
Console.WriteLine("Customer name: {0}", customer.Name);
model.BasicAck(deliveryArguments.DeliveryTag, false);
}
}
示例11: StartListening
public Task StartListening()
{
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
var task = Task.Factory.StartNew(() =>
{
var connection = _rabbitMqConnectionfactory.CreateConnection();
_channel = connection.CreateModel();
_channel.ExchangeDeclare(_rabbitMqExchangeName, "topic", true);
var queue = _channel.QueueDeclare("", false, false, true, null);
_channel.QueueBind(queue.QueueName, _rabbitMqExchangeName, "#");
var consumer = new QueueingBasicConsumer(_channel);
_channel.BasicConsume(queue.QueueName, false, consumer);
while (_channel.IsOpen && !token.IsCancellationRequested)
{
try
{
var ea = (BasicDeliverEventArgs) consumer.Queue.Dequeue();
_channel.BasicAck(ea.DeliveryTag, false);
Task.Factory.StartNew((handler) =>
{
var message =
RabbitMqMessageWrapper.Deserialize(ea.Body);
var handlersToInform =
(Action<RabbitMqMessageWrapper>) handler;
handlersToInform.Invoke(message);
}, _handler);
}catch(EndOfStreamException eose)
{
//ignore
}
}
},token);
return task;
}
示例12: GetResult
private static void GetResult(string queueName, IModel model)
{
var result = model.BasicGet(queueName, false);
if (result == null)
{
Console.WriteLine("Nothing left!");
return;
}
var msg = Encoding.UTF8.GetString(result.Body);
Console.WriteLine("Received {0}", msg);
Console.WriteLine("ACK'ing reciept of msg {0}", result.DeliveryTag);
model.BasicAck(result.DeliveryTag, false);
// Recursively get the other results
GetResult(queueName, model);
}
示例13: GetResult
private static void GetResult(string queueName, IModel model)
{
var result = model.BasicGet(queueName, false);
if (result == null)
{
Console.WriteLine("Nothing left!");
return;
}
var msg = result.Body.Deserialize<SomeMessage>().ToJson();
Console.WriteLine("Received {0}", msg);
Console.WriteLine("ACK'ing reciept of msg {0}", result.DeliveryTag);
model.BasicAck(result.DeliveryTag, false);
// Recursively get the other results
GetResult(queueName, model);
}
示例14: Filter
public IEnumerable<CurrentMessageInformation> Filter(IEnumerable<CurrentMessageInformation> input, IModel model)
{
foreach (var message in input)
{
var receivedSequence = BitConverter.ToUInt32((byte[])message.Headers[Headers.Sequence], 0);
var sequenceKey = new SequenceKey(message.Endpoint, message.MessageType);
if (Unknown(sequenceKey) || CorrectSequence(sequenceKey, receivedSequence))
{
nextSequences[sequenceKey] = receivedSequence + 1;
log.TraceFormat("Correct sequence {0} for key {1}", receivedSequence, sequenceKey);
yield return message;
foreach (var p in Filter(Pending(sequenceKey, receivedSequence), model))
yield return p;
}
else if (Unordered(sequenceKey, receivedSequence))
{
log.WarnFormat("Unexpected sequence {0} for key {1}. Was expecting {2}", receivedSequence, sequenceKey, nextSequences[sequenceKey]);
pendingMessages[sequenceKey].Add(receivedSequence, message);
}
else
{
log.DebugFormat("Filtering out (and acking) message sequence {0} - id {1} for key {2} as already processed",
receivedSequence,
message.MessageId,
sequenceKey);
try
{
model.BasicAck(message.DeliveryTag, false);
}
catch (AlreadyClosedException e)
{
log.Info("Could not ack filtered-out message because model was already closed", e);
}
catch (Exception e)
{
log.Warn("Could not ack filtered-out message for unknown cause", e);
}
}
}
}
示例15: ReceiveChunkedMessages
private static void ReceiveChunkedMessages(IModel model)
{
model.BasicQos(0, 1, false);
QueueingBasicConsumer consumer = new QueueingBasicConsumer(model);
model.BasicConsume(RabbitMqService.ChunkedMessageBufferedQueue, false, consumer);
while (true)
{
BasicDeliverEventArgs deliveryArguments = consumer.Queue.Dequeue() as BasicDeliverEventArgs;
Console.WriteLine("Received a chunk!");
IDictionary<string, object> headers = deliveryArguments.BasicProperties.Headers;
string randomFileName = Encoding.UTF8.GetString((headers["output-file"] as byte[]));
bool isLastChunk = Convert.ToBoolean(headers["finished"]);
string localFileName = string.Concat(@"c:\", randomFileName);
using (FileStream fileStream = new FileStream(localFileName, FileMode.Append, FileAccess.Write))
{
fileStream.Write(deliveryArguments.Body, 0, deliveryArguments.Body.Length);
fileStream.Flush();
}
Console.WriteLine("Chunk saved. Finished? {0}", isLastChunk);
model.BasicAck(deliveryArguments.DeliveryTag, false);
}
}