这是你可以使用的东西,
BrokerHelper.Publish("Aplan chaplam, chaliye aai mein :P");
以下是 BrokerHelper 类的定义。
public static class BrokerHelper
{
public static string Username = "guest";
public static string Password = "guest";
public static string VirtualHost = "/";
// "localhost" if rabbitMq is installed on the same server,
// else enter the ip address of the server where it is installed.
public static string HostName = "localhost";
public static string ExchangeName = "test-exchange";
public static string ExchangeTypeVal = ExchangeType.Direct;
public static string QueueName = "SomeQueue";
public static bool QueueExclusive = false;
public static bool QueueDurable = false;
public static bool QueueDelete = false;
public static string RoutingKey = "yasser";
public static IConnection Connection;
public static IModel Channel;
public static void Connect()
{
var factory = new ConnectionFactory();
factory.UserName = Username;
factory.Password = Password;
factory.VirtualHost = VirtualHost;
factory.Protocol = Protocols.FromEnvironment();
factory.HostName = HostName;
factory.Port = AmqpTcpEndpoint.UseDefaultPort;
Connection = factory.CreateConnection();
Channel = Connection.CreateModel();
}
public static void Disconnect()
{
Connection.Close(200, "Goodbye");
}
public static bool IsBrokerDisconnected()
{
if(Connection == null) return true;
if(Connection.IsOpen) return false;
return true;
}
public static void Publish(string message)
{
if (IsBrokerDisconnected()) Connect();
Channel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
Channel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
Channel.QueueBind(QueueName, ExchangeName, RoutingKey);
var encodedMessage = Encoding.ASCII.GetBytes(message);
Channel.BasicPublish(ExchangeName, RoutingKey, null, encodedMessage);
Disconnect();
}
}
进一步阅读:RabbitMQ 与 C# .NET、ASP.NET 和 ASP.NET MVC 的介绍以及示例