Enable specifying the protocol version on connection setup. Avoid CLIENT SETNAME command when using HELLO

This commit is contained in:
filipecosta90 2023-04-29 21:36:46 +01:00
parent f1c2e3261e
commit 959c94037c
2 changed files with 16 additions and 2 deletions

View File

@ -133,6 +133,11 @@ type Options struct {
// Enables read only queries on slave/follower nodes. // Enables read only queries on slave/follower nodes.
readOnly bool readOnly bool
// Protocol Version
// Redis version 6 and above supports two protocols: the old protocol, RESP2, and a new one introduced with Redis 6, RESP3.
// Default is 3.
ProtocolVersion int
} }
func (opt *Options) init() { func (opt *Options) init() {
@ -199,6 +204,13 @@ func (opt *Options) init() {
case 0: case 0:
opt.MaxRetryBackoff = 512 * time.Millisecond opt.MaxRetryBackoff = 512 * time.Millisecond
} }
// If no ProtocolVersion is specified we default to 3.
// RESP3 has certain advantages since when the connection is in this mode,
// Redis is able to reply with more semantical replies.
if opt.ProtocolVersion != 2 && opt.ProtocolVersion != 3 {
opt.ProtocolVersion = 3
}
} }
func (opt *Options) clone() *Options { func (opt *Options) clone() *Options {

View File

@ -279,11 +279,13 @@ func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error {
conn := newConn(c.opt, connPool) conn := newConn(c.opt, connPool)
var auth bool var auth bool
var clientNameSet bool
// for redis-server versions that do not support the HELLO command, // for redis-server versions that do not support the HELLO command,
// RESP2 will continue to be used. // RESP2 will continue to be used.
if err := conn.Hello(ctx, 3, username, password, "").Err(); err == nil { if err := conn.Hello(ctx, c.opt.ProtocolVersion, username, password, c.opt.ClientName).Err(); err == nil {
auth = true auth = true
clientNameSet = true
} else if !isRedisError(err) { } else if !isRedisError(err) {
// When the server responds with the RESP protocol and the result is not a normal // When the server responds with the RESP protocol and the result is not a normal
// execution result of the HELLO command, we consider it to be an indication that // execution result of the HELLO command, we consider it to be an indication that
@ -312,7 +314,7 @@ func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error {
pipe.ReadOnly(ctx) pipe.ReadOnly(ctx)
} }
if c.opt.ClientName != "" { if !clientNameSet && c.opt.ClientName != "" {
pipe.ClientSetName(ctx, c.opt.ClientName) pipe.ClientSetName(ctx, c.opt.ClientName)
} }