How to use RabbitMQ list of hosts connection parameter

天大地大妈咪最大 提交于 2019-12-22 10:23:23

问题


I'm trying to use the IList<string> parameter when creating a connection in the C# rabbitMQ library:

IConnection CreateConnection(IList hostnames)

My code is as follows:

    private IConnection CreateConnection()
    {
        var connectionFactory = new ConnectionFactory
        {
            UserName = _userName,
            Password = _password,
            VirtualHost = _vhost,
            AutomaticRecoveryEnabled = DEFAULT_AUTO_RECOVER,
            RequestedHeartbeat = HEARTBEAT_TIMEOUT_SECONDS,
            Port = AmqpTcpEndpoint.UseDefaultPort,
        };
        // _hosts contains valid IPs "###.###.###.###"
        return connectionFactory.CreateConnection(_hosts);
    }

But regardless of what I suppose for the hosts parameter it doesn't seem to connect (I get "None of the specified endpoints were reachable")

Even if my list contains only one element.

Now, if I use the single host implementation like this, it works correctly:

    private IConnection CreateConnection()
    {
        var connectionFactory = new ConnectionFactory
        {
            UserName = _userName,
            Password = _password,
            VirtualHost = _vhost,
            AutomaticRecoveryEnabled = DEFAULT_AUTO_RECOVER,
            RequestedHeartbeat = HEARTBEAT_TIMEOUT_SECONDS,
            Port = AmqpTcpEndpoint.UseDefaultPort,
            HostName = _hosts.First() // or just one string
        };
        return connectionFactory.CreateConnection();
    }

I recognize that RabbitMQ suggests not storing the set of hosts on the client but I'm just trying to get their provided method to work.


回答1:


I think you might need to set a value for the HostnameSelector property of the connection factory

private IConnection CreateConnection()
{
    var connectionFactory = new ConnectionFactory
    {
        UserName = _userName,
        Password = _password,
        VirtualHost = _vhost,
        AutomaticRecoveryEnabled = DEFAULT_AUTO_RECOVER,
        RequestedHeartbeat = HEARTBEAT_TIMEOUT_SECONDS,
        Port = AmqpTcpEndpoint.UseDefaultPort,
        HostnameSelector = new RandomHostnameSelector()
    };
    // _hosts contains valid IPs "###.###.###.###"
    return connectionFactory.CreateConnection(_hosts);
}

RabbitMQ provides a RandomHostnameSelector

class RandomHostnameSelector : IHostnameSelector
{
    string IHostnameSelector.NextFrom(IList<string> options)
    {
        return options.RandomItem();
    }
}

Or you could create your own implementation of IHostnameSelector to have your own host selection strategy.



来源:https://stackoverflow.com/questions/36849789/how-to-use-rabbitmq-list-of-hosts-connection-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!