Last active
May 12, 2018 19:17
-
-
Save thiagoloureiro/ba6089cc795a2acc9c3e8bb34b9bac35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MessageBroker | |
{ | |
private ConnectionFactory _factory; | |
private IConnection _connection; | |
private IModel _channel; | |
public string QueueName { get; set; } | |
public void Connect() | |
{ | |
_factory = new ConnectionFactory() { HostName = "hound.rmq.cloudamqp.com", VirtualHost = "-", UserName = "-", Password = "-" }; | |
_connection = _factory.CreateConnection(); | |
_channel = _connection.CreateModel(); | |
_channel.QueueDeclare(QueueName, true, false, false, null); | |
} | |
private void Cleanup() | |
{ | |
try | |
{ | |
if (_channel != null && _channel.IsOpen) | |
{ | |
_channel.Close(); | |
_channel = null; | |
} | |
if (_connection != null && _connection.IsOpen) | |
{ | |
_connection.Close(); | |
_connection = null; | |
} | |
} | |
catch (IOException ex) | |
{ | |
Console.WriteLine($"Cleanup failed! {ex.Message}"); | |
} | |
} | |
public bool WriteMessageOnQueue(string queueName, string message) | |
{ | |
try | |
{ | |
QueueName = queueName; | |
Connect(); | |
_channel.BasicPublish(string.Empty, queueName, null, Encoding.ASCII.GetBytes(message)); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
return false; | |
} | |
finally | |
{ | |
Cleanup(); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment