Skip to content

Instantly share code, notes, and snippets.

@gavi
Created December 28, 2019 17:11
Show Gist options
  • Select an option

  • Save gavi/c1cf8eefa4b101b1de3fd30affb4103f to your computer and use it in GitHub Desktop.

Select an option

Save gavi/c1cf8eefa4b101b1de3fd30affb4103f to your computer and use it in GitHub Desktop.

Revisions

  1. gavi created this gist Dec 28, 2019.
    72 changes: 72 additions & 0 deletions SBRabbit.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    using System;
    using System.Text;
    using RabbitMQ.Client;
    using RabbitMQ.Client.Events;

    namespace SBRabbit{
    class Program{
    static void Usage(){
    Console.WriteLine("SBRabbit <publish|susbscribe>");
    }
    public static void Main(string[] args){
    if(args.Length!=1){
    Usage();
    }
    else{
    if(args[0]=="susbscribe"){
    Subscribe();
    }
    else if(args[0]=="publish"){
    Console.Write("Enter Message:");
    string message = Console.ReadLine();
    Publish(message);
    }
    }
    }

    static void Subscribe(){
    var factory = new ConnectionFactory(){HostName = "localhost"};
    using(var connection = factory.CreateConnection()){
    using(var channel=connection.CreateModel()){
    channel.QueueDeclare(queue: "hello",
    durable: false,
    exclusive: false,
    autoDelete: false,
    arguments: null);
    var consumer = new EventingBasicConsumer(channel);
    consumer.Received += (model, ea) =>
    {
    var body = ea.Body;
    var message = Encoding.UTF8.GetString(body);
    Console.WriteLine(" [x] Received {0}", message);
    Console.WriteLine(" [x] Done");
    };
    channel.BasicConsume(queue: "hello", autoAck: true, consumer: consumer);
    //Pause Execution Here
    Console.ReadLine();
    }
    }
    }

    static void Publish(string message){
    var factory = new ConnectionFactory(){HostName = "localhost"};
    using (var connection = factory.CreateConnection()){
    using(var channel = connection.CreateModel()){
    channel.QueueDeclare(queue: "hello",
    durable: false,
    exclusive: false,
    autoDelete: false,
    arguments: null);

    var body = Encoding.UTF8.GetBytes(message);

    channel.BasicPublish(exchange: "",
    routingKey: "hello",
    basicProperties: null,
    body: body);
    Console.WriteLine(" [x] Sent {0}", message);
    }
    }
    }
    }
    }