Skip to content

Instantly share code, notes, and snippets.

@stianeikeland
Created November 30, 2012 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stianeikeland/4174931 to your computer and use it in GitHub Desktop.
Save stianeikeland/4174931 to your computer and use it in GitHub Desktop.
RabbitMQ consumer/producer
using System;
using System.Reactive.Linq;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitTest
{
class Program
{
private static void Main(string[] args)
{
const string exchange = "postkontor";
const string key = "adresse";
var factory = new ConnectionFactory
{
Protocol = Protocols.FromEnvironment(),
HostName = "192.168.73.77"
};
Console.WriteLine("Connecting..");
using (var conn = factory.CreateConnection())
using (var channel = conn.CreateModel())
{
channel.ExchangeDeclare(exchange, ExchangeType.Topic);
Console.WriteLine("Connected");
SetUpProducer(channel, exchange, key);
SetUpConsumer(channel, exchange, key);
Console.ReadKey();
}
}
private static void SetUpConsumer(IModel channel, string exchange, string key)
{
var queue = channel.QueueDeclare();
var consumer = new EventingBasicConsumer();
consumer.Received += (o, e) =>
{
var data = Encoding.UTF8.GetString(e.Body);
Console.WriteLine(data);
};
Console.WriteLine("Listening..");
channel.BasicConsume(queue, true, consumer);
channel.QueueBind(queue, exchange, key);
}
private static void SetUpProducer(IModel channel, string exchange, string key)
{
Observable.Interval(TimeSpan.FromSeconds(1))
.Subscribe(x =>
{
Console.WriteLine("Publishing: " + x);
channel.BasicPublish(
exchange,
key,
null,
Encoding.UTF8.GetBytes("Viktig melding: " + x)
);
}
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment