RabbitMQ-如何模拟连接超时以测试Polly的实现

时间:2019-06-19 12:03:24

标签: .net sockets rabbitmq timeout polly

我正在尝试使用Polly为RabbitMQ客户端实现“等待并重试”功能。目前,我知道我的实现方式不正确(请参见下文),但是很难以正确的方式实现,因为我不知道如何模拟连接超时或其他一些与网络相关的错误...

因此,我至少需要回答一个问题:)

  • 有没有一种方法可以模拟RabbitMQ的连接超时?

  • Poly for RabbitMQ的正确实现是什么?

我使用RabbitMQ网络客户端:https://www.rabbitmq.com/dotnet.html

我当前的实现是这样的(伪代码):

private readonly IConnectionFactory _factory;
private IConnection _connection;
private IModel _channel;

public void Publish(...)
{
    var policy = Policy.Handle<Exception>().WaitAndRetry(...);
    policy.Execute(() => 
    {
        var channel = GetChannel();
        channel.BasicPublish(...);
    });
}

private IConnection GetConnection()
{
    if (_connection != null && _connection.IsOpen)
        return _connection;
    _connection?.Dispose();
    _connection = _factory.CreateConnection();
    return _connection;
}

private IModel GetChannel()
{
    if (_channel != null && _channel.IsOpen && !_channel.IsClosed)
        return _channel;
    _channel?.Dispose();
    var connection = GetConnection();
    _channel = connection.CreateModel();
    return _channel;
}

当前,当我收到超时(未模拟)时,Polly正确检测到它。异常消息是:

Unable to write data to the transport connection: Connection timed out. (source: System.Net.Sockets, type: IOException)

当它尝试执行重试时,我得到一个新的异常:

Unable to write data to the transport connection: Operation canceled. (source: System.Net.Sockets, type: IOException)

谢谢。

0 个答案:

没有答案
相关问题