SoFunction
Updated on 2025-03-05

How to understand Go language operation Redis in one article

Preface

RedisIt is an open source in-memory database in project developmentredisIt is also used frequently. This article introduces Go languagego-redisBasic use of the library. Interested friends can refer to it, and I hope it will be helpful to everyone.

Install dependency package

Use third-party library go-redis in Go language

go-redis supports Redis connecting sentinels and cluster modes.

Download and install using the following command:

go get -u /go-redis/redis/v8

Connect to redis

NewgoDocuments, introduced in the project/go-redis/redis/v8

initialization, without saying much nonsense, just upload the code.

package main

import (
	"context"
	"fmt"
	"/go-redis/redis/v8"
)

// Define a global variablevar redisdb *
var ctx = ()

func initRedis()(err error){
	redisdb = (&{
		Addr: "127.0.0.1:6379",  //Specify		Password: "",
		DB:0,		// There are 16 libraries in total, just specify one of them	})
	_,err = (ctx).Result()
	return
}

func main() {
	err := initRedis()
	if err != nil {
		("connect redis failed! err : %v\n",err)
		return
	}
	("Redis connection succeeded!")
}

Notice:The latest version ofgo-redisThe relevant commands of the library need to be passedparameter.

Redis connection pool

Golang to redis, you can also connect to the redis connection pool. The process is as follows:

(1) Initialize a certain number of connections in advance and invest in the connection pool;

(2) When go needs to operate redis, just take out the connection from the connection pool;

(3) This can save time to temporarily obtain redis, thereby improving efficiency;

go-redisThe module comes with its own connection pool, and all parameters are optional. The parameter configuration example is as follows:

redisdb = (&{
		Addr: "127.0.0.1:6379",  //Specify		Password: "",
		DB:0,		// There are 16 libraries in total, just specify one of them
		//Connection pool capacity and number of idle connections		PoolSize:     15, // The maximum number of socket connections in the connection pool is 4 times the number of CPUs, 4 *		MinIdleConns: 10, //Create a specified number of Idle connections during the startup phase, and maintain the idle state for a long time at least the specified number;.
		//time out		DialTimeout:  5 * , //Connection establishment timeout, default is 5 seconds.		ReadTimeout:  3 * , //Read timeout, default 3 seconds, -1 means cancel read timeout		WriteTimeout: 3 * , //Write timeout, default is equal to read timeout		PoolTimeout:  4 * , //When all connections are busy, the maximum waiting time for the client to wait for available connections is default to read timeout +1 second.
		//Idle connection check includes IdleTimeout, MaxConnAge		IdleCheckFrequency: 60 * , //The period of idle connection checking is 1 minute by default. -1 means no periodic checking is performed, and only idle connections are processed when the client obtains the connection.		IdleTimeout:        5 * ,  //Idle timeout, default 5 minutes, -1 means canceling the idle timeout check		MaxConnAge:         0 * ,  //The duration of the connection is counted from creation. If the connection exceeds the specified duration, the default is 0, which means that the connection with a longer survival time is not closed.
		//Retry policy when command execution fails		MaxRetries:      0,                      // How many times can I try again when the command fails? The default is 0, that is, no retry		MinRetryBackoff: 8 * ,   //The lower limit of the retry interval time is calculated each time, the default is 8 milliseconds, -1 means canceling the interval		MaxRetryBackoff: 512 * , //The upper limit of the retry interval time is calculated each time, the default is 512 milliseconds, -1 means canceling the interval
		//Customize connection functions		Dialer: func(ctx , network, addr string) (, error) {
			netDialer := &{
				Timeout:   5 * ,
				KeepAlive: 5 * ,
			}
			return ("tcp", "127.0.0.1:6379")
		},

		//Hook function		OnConnect: func(ctx , conn *) error { //This hook function will be called only if the client needs to obtain a connection from the connection pool when executing the command.			("conn=%v\n", conn)
			return nil
		},
	})

Summarize

This article mainly introduces you how to use itgoThird-party packagego-redisconnectRedis

For more details, please checkOfficial Documentation

This is the article about understanding the method of operating Redis in Go language. For more related content on operating Redis in Go language, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!