How can I specify two JSON objects in one RabbitMQ queue?

I want to be able to send two different JSON messages in the same queue. How do I, in C #, determine what type of message was received so that I can deserialize the message to the appropriate object? Should I use a message header or create another queue? The queue for the type of message seems excessive to me. Thank!

Additional data: I have a Windows service that handles "running". The startup identifier is assigned by another system, and the identifier is deleted in the queue. My service receives an identifier and starts work. An object is created for each run. Right now, if I want to cancel the job, I have to stop the service. But it stops working. I wanted to add a method like CancelRun, but all I need is a run identifier. That way I could use the same JSON (same class). The two queues would not be terrible, but I thought it would be wise to add a type or something to the custom header.

+4
source share
5 answers

. , JSON, .

IBasicProperties props = model.CreateBasicProperties();
props.Headers = new Dictionary<string, object>();
props.Headers.Add("RequestType", "CancelRunRequest");

, , ( EventArg obj):

// Raise message received event
var args = new MessageReceivedArgs();
args.CorrelationId = response.BasicProperties.CorrelationId;
args.Message = Encoding.UTF8.GetString(response.Body);
args.Exchange = response.Exchange;
args.RoutingKey = response.RoutingKey;

if (response.BasicProperties.Headers != null && response.BasicProperties.Headers.ContainsKey("RequestType"))
{
args.RequestType = Encoding.UTF8.GetString((byte[])response.BasicProperties.Headers["RequestType"]);
}

MessageReceived(this, args);
model.BasicAck(response.DeliveryTag, false);

:

private void NewRunIdReceived(object p, MessageReceivedArgs e)
{

if(e.RequestType.ToUpper() == "CANCELRUNREQUEST")
{
    // This is a cancellation request
    CancelRun(e);
}
else
{
    // Default to startrun request for backwards compatibility.
    StartRun(e);
}
}
+3

, , . , , , , - . , , . - , , , .

+1

JSON , , JSON.

JSON, .

0

, , , Object IHaveType, , , .

ObjectType1 : HaveType 

public class HaveType { public string Type { get { this.GetType(); }}}

Json

[{Type: 'ObjectType1', ...[other object stuff]},{Type : 'ObjectType2',...}]
0

, sphair, , . , # , .

0

Source: https://habr.com/ru/post/1535574/


All Articles