i would like to publish/produce a message with some message id, like each message has a particular id..
And at the consumer end i would like to retrieve the messages by prividing the ID. suppose we have multiple consumers than each one should get only those messages which they requested t开发者_如何学JAVAhrough the message ids. (i hope i am clear enough).
Although its not by design and its better to use a database for that there is a way to do this using rabbitmq:
Publish a message with id:
var message = "some message";
var messageId = Guid.NewGuid().ToString();
var factory = new ConnectionFactory { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
IBasicProperties props = channel.CreateBasicProperties();
props.MessageId = messageId;
byte[] messageBodyBytes = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "queueName", true, props, messageBodyBytes);
}
Get a message by id:
var messageId = "id";
var factory = new ConnectionFactory { HostName = "localhost" };
using (var connection = _factory.CreateConnection())
using (var channel = connection.CreateModel())
{
var queueDeclareResponse = channel.QueueDeclare("queueName", true, true, false, null);
for (int i = 0; i < queueDeclareResponse.MessageCount; i++)
{
var result = channel.BasicGet("queueName", false);
var id = result.BasicProperties.MessageId;
if (id == messageId)
{
var body = result.Body;
var message = Encoding.UTF8.GetString(body);
//Do something with the message
channel.BasicAck(result.DeliveryTag, false);
break;
}
}
}
After channel
is disposed all messages that was not acked will requeue.
You might be better off using a database for this.
alexis (rabbitmq)
精彩评论