Skip to content

Instantly share code, notes, and snippets.

@kbaley
Created August 30, 2017 03:36
Show Gist options
  • Save kbaley/298a441f3cca6be0a96c7a88eda10c33 to your computer and use it in GitHub Desktop.
Save kbaley/298a441f3cca6be0a96c7a88eda10c33 to your computer and use it in GitHub Desktop.
using NServiceBus;
public class MyMessage :
IMessage
{
public bool Done { get; set; }
}
using System;
using NServiceBus;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Collections.Generic;
using NServiceBus.MessageInterfaces.MessageMapper.Reflection;
using NServiceBus.Serializers.Json;
class Program
{
static void Main()
{
SendMessages();
// Receive();
}
static void SendMessages()
{
Console.Title = "Samples.RabbitMQ.Simple";
var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.RabbitMQ.Simple");
var transport = busConfiguration.UseTransport<RabbitMQTransport>();
transport.ConnectionString("host=localhost");
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.EnableInstallers();
using (var bus = Bus.Create(busConfiguration).Start())
{
MyMessage myMessage;
for (int i = 0; i < 100; i++)
{
myMessage = new MyMessage
{
Done = false
};
bus.SendLocal(myMessage);
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
static void Receive()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "Samples.RabbitMQ.Simple", durable: true, exclusive: false, autoDelete: false, arguments: null);
var consumer = new EventingBasicConsumer(channel);
var mapper = new MessageMapper();
var types = new List<Type>
{
typeof(MyMessage)
};
mapper.Initialize(types);
var serializer = new JsonMessageSerializer(mapper);
var json = serializer.SerializeObject(new MyMessage
{
Done = false
});
Console.WriteLine(json);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var messageBody = Encoding.UTF8.GetString(body);
serializer.Encoding = Encoding.UTF8;
var message = (MyMessage)serializer.DeserializeObject(messageBody, typeof(MyMessage));
Console.WriteLine(" [x] Received {0}", message.Done);
};
channel.BasicConsume(queue: "Samples.RabbitMQ.Simple", consumer: consumer, noAck: true);
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment