如何在Linux上的Mono上使用RabbitMQ

时间:2015-01-19 08:46:21

标签: mono rabbitmq

我应该使用哪个库等?我已将它与node.js一起使用,但我无法解决如何在linux上使用mono(C#)的问题。

1 个答案:

答案 0 :(得分:6)

几个小时后,我得到了一个基本样本。

首先,从www.rabbitmq.com/dotnet.html下载rabbitmq-dotnet-client-3.4.3-dotnet-3.5.zip

提取并添加对RabbitMQ.Client.dll的引用到您的项目。

using RabbitMQ.Client;

static public void Publish()
{
    ConnectionFactory factory = new ConnectionFactory();

    // The next six lines are optional:
    factory.UserName = ConnectionFactory.DefaultUser;
    factory.Password = ConnectionFactory.DefaultPass;
    factory.VirtualHost = ConnectionFactory.DefaultVHost;
    factory.HostName = "localhost";
    factory.Port     = AmqpTcpEndpoint.UseDefaultPort;

    // You also could do this instead:
    factory.Uri = "amqp://localhost";

    IConnection connection = factory.CreateConnection();

    IModel channel = connection.CreateModel();

    channel.QueueDeclare("hello-world-queue", // queue
        false, // durable
        false, // exclusive
        false, // autoDelete
        null); // arguments

    byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
    channel.BasicPublish(string.Empty, // exchange
        "hello-world-queue", // routingKey
        null, // basicProperties
        message); // body

    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
    channel.Close();
    connection.Close();
}

static public void Subscribe()
{
    ConnectionFactory connectionFactory = new ConnectionFactory();
    IConnection connection = connectionFactory.CreateConnection();
    IModel channel = connection.CreateModel();
    channel.QueueDeclare("hello-world-queue", false, false, false, null);

    // BasicGet: Retrieve an individual message, if one is available.
    // Returns null if the server answers that no messages are currently available. 
    BasicGetResult result = channel.BasicGet("hello-world-queue", // queue
        true); // noAck (true=auto ack, false=we must call BasicAck ourselves)

    if (result != null)
    {
        string message = Encoding.UTF8.GetString(result.Body);
        Console.WriteLine(message);

        // If the noAck parameter to BasicGet was false then:
        // channel.BasicAck(result.DeliveryTag // deliveryTag
        //  false); // multiple (not sure what this means)
    }
    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
    channel.Close();
    connection.Close();
}

我希望能帮助别人。