2013-12-11 55 views
0

我在我的web应用程序(Asp.net-MVC 4.0)中使用rabbit-mq。我的要求是发送消息给特定的用户。假设如果user1在线并且他通过rabbit-Mq向user2发送消息。它应该只被“user2”接收。我使用的代码是一个将消息存储在队列中的模板,每当用户点击接收时,他都会得到这个消息,但在我的情况下没有特定用户的限制。任何人都可以得到那个错误的信息,我必须处理。请帮助我解决这个问题。发送邮件由rabbitMq

我们在rabbit-Mq中有什么东西可以区分正确的消息和正确的用户/消费者吗?我们可以设置一个带有消息的密钥并在接收时检查密钥吗? 这可能吗?

下面我写我使用的发送和接收消息

public ActionResult SendMessage(MessagingModel ObjModel) 
     {  var factory = new ConnectionFactory() { HostName = "localhost" }; 
       using (var connection = factory.CreateConnection()) 
       { 
        using (var channel = connection.CreateModel()) 
        { 
         Message = ObjModel.Message; 
         channel.QueueDeclare("MessageQueue", true, false, false, null); 
         var body = Encoding.UTF8.GetBytes(ObjModel.Message); 
    channel.BasicPublish("", "MessageQueue", null, body); 
} 
} 
} 

    public JsonResult RecieveMessage() 
     { 
    var factory = new ConnectionFactory() { HostName = "localhost" }; 
       using (var connection = factory.CreateConnection()) 
       { 
        using (var channel = connection.CreateModel()) 
        { 
         channel.QueueDeclare("MessageQueue", true, false, false, null); 
         bool noAck = true; 
         BasicGetResult result = channel.BasicGet("MessageQueue", noAck); 
         if (result == null) 
         { 
          Message = "No Messages Found."; 
         } 
         else 
         { 
          IBasicProperties props = result.BasicProperties; 
          byte[] Body = result.Body; 
          Message = Encoding.Default.GetString(Body); 
         } 
        } 
       } 

回答

1

首先代码,你一定要记住下面的事情:

  • 在RabbitMQ的所有消息在交流中公布。
  • 队列绑定到交换。
  • 事件如果您直接发布消息到队列中,实际上它仍然通过默认交换 - (AMPQ默认值)。
  • 有不同种类的交流。你可以阅读一些有关的交流在这里:https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html

在你情况下,你可能会考虑使用主题或标题交流,但在这种情况下,你应该为每个用户 有一个队列,如果数量系统中的用户很大,那么它将非常耗费资源。

你也可以添加特定的头给你消息:

var props = model.CreateBasicProperties(); 
props.Headers.Add("UserId", userId); 

,然后在RecieveMessage()方法后,从队列中读取消息,看到这个标题,如果消息用于当前用户 - 接受它,并确认此消息,否则 不确认此消息。
但这是不好的解决方案。我只是将队列中的消息保存到数据库中,然后将它们读出来进行用户筛选。