using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Channels; using System.Threading.Tasks; namespace HelloWorld { public class Sender : IDisposable { private readonly ConnectionFactory _connectionFactory; private readonly IConnection _connection; private readonly IModel _channel; private readonly string _queueName; public Sender(string brockerHost, string brockerUsername, string brockerPassword, string queueName) { _queueName = queueName; _connectionFactory = new ConnectionFactory() { HostName = brockerHost, UserName = brockerUsername, Password = brockerPassword }; _connection = _connectionFactory.CreateConnection(); _channel = _connection.CreateModel(); _channel.QueueDeclare( queue: _queueName, durable: true, exclusive: false, autoDelete: false, arguments: null); } public bool SendMessageToQueue(string messageText) { try { var messageBody = Encoding.UTF8.GetBytes(messageText); var properties = _channel.CreateBasicProperties(); properties.Persistent = true; _channel.BasicPublish(exchange: string.Empty, routingKey: _queueName, basicProperties: properties, body: messageBody); return true; } catch (Exception ex) { Console.WriteLine(ex); } return false; } ~Sender() => Dispose(); public void Dispose() { _connection.Dispose(); _channel.Dispose(); } } }