简体   繁体   中英

How to determine if I need a new TCP connection from a Rust io::Error?

I'm using the redis crate to talk to a Redis server over TCP from Rust. If the TCP connection for some reason goes down (eg server crash), I want to try to reconnect (with some backoff so as not to clog the server) by creating a new Connection .

My problem is how to determine when to reconnect? The redis crate throws RedisError 's, and some of these contain an io::Error . How do I determine which io::Error 's require a new connection, and which don't? I guess I will have to match on io::Error::kind() along the lines of this:

use std::io;

fn needs_new_connection(error: &io::Error) -> bool {
    match error.kind() {
        io::ErrorKind::ConnectionReset |
        io::ErrorKind::ConnectionAborted => true,
        _ => false,
    }
}

But what ErrorKind 's should be in there? Should I add NotConnected ? TimedOut ? Others? Or should I use some completely different approach?

While I am using Redis, I think it should be fine to treat this as a question purely about TCP. I'm not supporting Unix sockets.

You should ideally be working off the RedisError itself to figure out what happened and if you need to reconnect. There are a bunch of useful methods defined on that type to help you figure out what you need to do:

  • is_io_error() will return true if the error was due to I/O, and is_timeout() will return true if the cause was I/O timeout
  • is_connection_dropped() returns true if your connection was dropped
  • is_connection_refusal() returns true if your connection was actively refused (or if the server flat-out does not exist)

These methods will allow you to pinpoint which type of connection error it was without having to enumerate every possible variant. In particular, to cover most cases, you'll be interested in combining them. In this situation, I'd honestly go (error.is_io_error() || error.is_connection_dropped()) && !error.is_connection_refusal() . That covers every accidental I/O failure case, while making sure to avoid cases such as invalid credentials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM