问题
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