Skip to content

Instantly share code, notes, and snippets.

@iporsut
Last active June 7, 2021 10:13
Show Gist options
  • Save iporsut/497f639e3727e83d8d554088ee32256a to your computer and use it in GitHub Desktop.
Save iporsut/497f639e3727e83d8d554088ee32256a to your computer and use it in GitHub Desktop.
Example Rabit C# Client
using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Receive
{
class Program
{
public static async Task Main()
{
var myChannel = Channel.CreateUnbounded<string>();
ConnectionFactory factory = CreateRabbitMQFactory();
factory.DispatchConsumersAsync = true;
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
FetchMessageAndWriteToChannel(myChannel, channel);
await InvokeExternalService(myChannel);
ConnectionFactory CreateRabbitMQFactory()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
factory.UserName = "admin";
factory.Password = "Admin@123";
return factory;
}
async Task InvokeExternalService(Channel<string> myChannel)
{
await Task.Run(async () =>
{
while (true)
{
var item = await myChannel.Reader.ReadAsync();
Console.WriteLine("From channel t0 somewhere->" + item);
}
});
}
void FetchMessageAndWriteToChannel(Channel<string> myChannel, IModel channel)
{
channel.QueueDeclare("two.port", true, false, false, null);
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += async (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine("From rabbit to channel->" + message);
await myChannel.Writer.WriteAsync(message);
};
channel.BasicConsume("two.port", true, consumer);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment