连接到 RabbitMQ,方法级最佳实践?

发布于 2024-11-20 13:48:48 字数 2279 浏览 11 评论 0原文

我有一个使用rabbitmq 读取和写入消息的类。我不想在此类的构造函数或读写方法中包含与连接相关的信息。相反,我想在使用写入和读取方法时建立连接。解决这个问题的最佳方法/做法是什么?

//编辑1

public class Rabbit : IMessageBus
{   
    // Implementation of methods for Rabbit class go here
    private List<string> publishQ = new List<string>();
    private List<string> subscribeQ = new List<string>();

    ConnectionFactory factory = null;
    IConnection connection = null;
    IModel channel = null;  
    QueueingBasicConsumer consumer = null;  


    public void write ( Measurement m1 )
    {
        byte[] body = Measurement.AltSerialize( m1 );

        foreach (string queue in publishQ) 
        {
            channel.BasicPublish("", queue, null, body);
            Console.WriteLine("\n  [x] Sent to queue {0}.", queue);
        }
    }

    public void publish(string queueName)
    {   
        channel.QueueDeclare(queueName, true, false, false, null); //durable=true

        publishQ.Add(queueName); //and, add it the list of queue names to publish to
    }

    public Measurement read() 
    {       
        foreach (string queue in subscribeQ) 
        {
            channel.BasicConsume(queue, true, consumer);
        }

        System.Console.WriteLine(" [*] Waiting for messages." +
                                "To exit press CTRL+C");
        BasicDeliverEventArgs ea = 
            (BasicDeliverEventArgs)consumer.Queue.Dequeue();

        return Measurement.AltDeSerialize(ea.Body);
    }

    public void subscribe(string queueName)
    {
        channel.QueueDeclare(queueName, true, false, false, null);
        subscribeQ.Add(queueName);
    }

    public static string MsgSysName;
    public string MsgSys
    {
        get 
        { 
            return MsgSysName;
        }
        set
        {
            MsgSysName = value;
        }
    }

    public Rabbit(string _msgSys) //Constructor
    {   
        factory = new ConnectionFactory();
        factory.HostName = "localhost"; 
        connection = factory.CreateConnection();
        channel = connection.CreateModel();
        consumer = new QueueingBasicConsumer(channel);

        System.Console.WriteLine("\nMsgSys: RabbitMQ");
        MsgSys = _msgSys;
    }

    ~Rabbit()
    {
        //
    }   
}

I have a class that reads and writes messages using rabbitmq. I don't want to have connection related info in this class's constructor nor inside the read and write methods. Instead, I want to make a connection when I use the write and read methods. What is the best way/practice to go about tackling this issue?

//Edit 1

public class Rabbit : IMessageBus
{   
    // Implementation of methods for Rabbit class go here
    private List<string> publishQ = new List<string>();
    private List<string> subscribeQ = new List<string>();

    ConnectionFactory factory = null;
    IConnection connection = null;
    IModel channel = null;  
    QueueingBasicConsumer consumer = null;  


    public void write ( Measurement m1 )
    {
        byte[] body = Measurement.AltSerialize( m1 );

        foreach (string queue in publishQ) 
        {
            channel.BasicPublish("", queue, null, body);
            Console.WriteLine("\n  [x] Sent to queue {0}.", queue);
        }
    }

    public void publish(string queueName)
    {   
        channel.QueueDeclare(queueName, true, false, false, null); //durable=true

        publishQ.Add(queueName); //and, add it the list of queue names to publish to
    }

    public Measurement read() 
    {       
        foreach (string queue in subscribeQ) 
        {
            channel.BasicConsume(queue, true, consumer);
        }

        System.Console.WriteLine(" [*] Waiting for messages." +
                                "To exit press CTRL+C");
        BasicDeliverEventArgs ea = 
            (BasicDeliverEventArgs)consumer.Queue.Dequeue();

        return Measurement.AltDeSerialize(ea.Body);
    }

    public void subscribe(string queueName)
    {
        channel.QueueDeclare(queueName, true, false, false, null);
        subscribeQ.Add(queueName);
    }

    public static string MsgSysName;
    public string MsgSys
    {
        get 
        { 
            return MsgSysName;
        }
        set
        {
            MsgSysName = value;
        }
    }

    public Rabbit(string _msgSys) //Constructor
    {   
        factory = new ConnectionFactory();
        factory.HostName = "localhost"; 
        connection = factory.CreateConnection();
        channel = connection.CreateModel();
        consumer = new QueueingBasicConsumer(channel);

        System.Console.WriteLine("\nMsgSys: RabbitMQ");
        MsgSys = _msgSys;
    }

    ~Rabbit()
    {
        //
    }   
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2024-11-27 13:48:48

您是否考虑过将 Func 传递到构造函数中?换句话说,有一种方法可以让您在需要时获得连接

(显然你需要在某个地方传递连接信息,除非你要静态访问它......不寒而栗。)

编辑:好的,我不熟悉 RabbitMQ,但假设它有某种实现 IDisposableConnection 类,它看起来像这样:

public class MessageHandler
{
    private readonly Func<Connection> connectionProvider;

    public MessageHander(Func<Connection> connectionProvider)
    {
        this.connectionProvider = connectionProvider;
    }

    public void WriteMessage(string message)
    {
        using (Connection connection = connectionProvider.Invoke())
        {
            connection.DoSomething(message);
        }
    }
}

然后用类似的东西创建它:

MessageHandler handler = new MessageHandler(() => new Connection(server));

现在,如果涉及到任何更“有趣”的内容,您可能想要到编写一个单独的 ConnectionProvider 类。当然,RabbitMQ 可能有一些示例代码 - 您应该首先查阅它们及其文档,因为我真的不知道我在说什么:)

Have you considered passing a Func<Connection> into the constructor? In other words, a way that you can get a connection when you want it?

(Obviously you need to pass the connection information in somewhere, unless you're going to access it statically... shudder.)

EDIT: Okay, I'm not familiar with RabbitMQ, but assuming it has some sort of Connection class which implements IDisposable, it would look something like this:

public class MessageHandler
{
    private readonly Func<Connection> connectionProvider;

    public MessageHander(Func<Connection> connectionProvider)
    {
        this.connectionProvider = connectionProvider;
    }

    public void WriteMessage(string message)
    {
        using (Connection connection = connectionProvider.Invoke())
        {
            connection.DoSomething(message);
        }
    }
}

Then create it with something like:

MessageHandler handler = new MessageHandler(() => new Connection(server));

Now if there's anything more "interesting" involved, you may want to write a separate ConnectionProvider class. Of course, RabbitMQ probably has some sample code - you should consult that and their documentation first, as I don't really know what I'm talking about :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文