From 959c94037c1e32f93b76b4648081f078587264c2 Mon Sep 17 00:00:00 2001 From: filipecosta90 Date: Sat, 29 Apr 2023 21:36:46 +0100 Subject: [PATCH] Enable specifying the protocol version on connection setup. Avoid CLIENT SETNAME command when using HELLO --- options.go | 12 ++++++++++++ redis.go | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/options.go b/options.go index a4af5884..d821b444 100644 --- a/options.go +++ b/options.go @@ -133,6 +133,11 @@ type Options struct { // Enables read only queries on slave/follower nodes. 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() { @@ -199,6 +204,13 @@ func (opt *Options) init() { case 0: 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 { diff --git a/redis.go b/redis.go index cae12f8c..f46ee76b 100644 --- a/redis.go +++ b/redis.go @@ -279,11 +279,13 @@ func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error { conn := newConn(c.opt, connPool) var auth bool + var clientNameSet bool // for redis-server versions that do not support the HELLO command, // 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 + clientNameSet = true } else if !isRedisError(err) { // 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 @@ -312,7 +314,7 @@ func (c *baseClient) initConn(ctx context.Context, cn *pool.Conn) error { pipe.ReadOnly(ctx) } - if c.opt.ClientName != "" { + if !clientNameSet && c.opt.ClientName != "" { pipe.ClientSetName(ctx, c.opt.ClientName) }