如何尝试捕获对离线 RPC 服务器的 RPC 调用?

How to try-catch a RPC call to an offline RPC server?

如果我们向联机的服务器发出 RPC 调用但不 运行 RPC 服务器,我正在搜索如何继续。

我在我的代码中唯一做的就是 ping 我们的故障转移 IP 地址以检查服务器是否 运行nning,但是如果我用我的 C# 应用程序进行 RPC 调用,它就会崩溃。

RPC调用函数:

public string Call(string message)
{
    var corrId = Guid.NewGuid().ToString();
    var props = channel.CreateBasicProperties();
    props.ReplyTo = replyQueueName;
    props.CorrelationId = corrId;

    var messageBytes = Encoding.UTF8.GetBytes(message);
    channel.BasicPublish(exchange: "", routingKey: "rpc_queue", basicProperties: props, body: messageBytes);

    while(true)
    {
        var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
        if(ea.BasicProperties.CorrelationId == corrId)
        {
            return Encoding.UTF8.GetString(ea.Body);
        }
    }
}

有人有解决办法吗?

PS : RabbitMQ confesses to don't solve these following problems :

Our code is still pretty simplistic and doesn't try to solve more complex (but important) problems, like:

How should the client react if there are no servers running?

Should a client have some kind of timeout for the RPC?

谢谢。

对于遇到这个问题的人,我是这样解决的:

try
{
    var task = Task.Run(() => rpcClient.Call(data_encoded));
    if (task.Wait(TimeSpan.FromSeconds(3)))
    {
        response = task.Result;
    }
    else
    {
        throw new Exception("Timed out");
    }
    Console.WriteLine("RESPONSE : " + response);
}
catch (Exception e)
{
    // Some code here ...
}

我是 RabbitMQ 和 RPC 的新手,但在从我的客户端发出 RPC 调用之前,我正在使用以下检查来查看服务器是否处于活动状态:

private bool IsRpcServerAlive()
{
   // create a temporary channel since it will not be
   // reusable if an exception is thrown
   using (var tempChannel = connection.CreateModel())
   {
      try
      {
         // throws an exception if the Queue does not exist
         var declareResult = channel.QueueDeclarePassive("rpc_queue");
         // RPC server is the only consumer of the Queue
         return declareResult.ConsumerCount > 0;
      }
      catch (RabbitMQ.Client.Exceptions.OperationInterruptedException)
      {
         return false;
      }
   }
}

这对我有用,因为我的服务器是队列的唯一消费者。有关被动声明的更多信息,请参阅 https://www.rabbitmq.com/dotnet-api-guide.html#passive-declaration