在 Redis 连接失败时重试

huangapple go评论82阅读模式
英文:

Retry on redis connection failure

问题

红果为什么决定不导出errorConn类型呢?这样可以让应用程序对连接失败有特定的错误处理方式。按照目前的实现,应用程序必须将这些错误处理为通用错误。

例如,我们的应用程序通常不关心单个PUT操作是否失败,但如果问题是Redis连接失败或Redis池耗尽,继续进行下一个PUT操作(特别是如果需要打开新连接)是一个坏主意。我们应该停下来并重试(使用指数退避),直到连接恢复。

代码中的示例显示,如果连接池耗尽,redigo会返回一个通用错误。

英文:

Wondering why redigo decided not to export the errorConn type, which would allow applications to have specific error handling for connection failures. As implemented, applications have to handle these as generic errors.

For example, our application generally doesn't care if a single PUT fails, but if the issue is a redis connection failure or redis pool being exhausted, moving on to the next PUT (especially if it requires opening a new connection) is a bad idea. We should stop and retry (with exponential backoff) until the connection comes back.

Code example where redigo returns a generic error if the connection pool is exhausted

答案1

得分: 0

你的链接中的代码行返回了两个相应类型的值:(Conn, error)

if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
	p.mu.Unlock()
	return errorConn{ErrPoolExhausted}, ErrPoolExhausted
}

类型Conn是一个具有Err方法的接口。

// Err返回一个非nil值,表示连接不可用。
Err() error

因此,要获取底层错误,你可以选择:

  • 在第一个返回值上调用Err方法;或者
  • 检查第二个error返回值。

顺便提一下,比较错误的推荐方式是使用标准库errors包中的errors.Is和/或errors.As

英文:

The lines of code in your link return two values of the respective types: (Conn, error).

if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
	p.mu.Unlock()
	return errorConn{ErrPoolExhausted}, ErrPoolExhausted
}

The type Conn is an interface with an Err method.

// Err returns a non-nil value when the connection is not usable.
Err() error

So to obtain the underlying error, you can either:

  • call the Err method on the first return value; or
  • check the second error return value.

As a side note, the recommended way to compare errors is by using errors.Is and/or errors.As from the standard library errors package.

huangapple
  • 本文由 发表于 2021年8月24日 01:21:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68896634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定