Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

We often use Redis in our development. There are many application scenarios of Redis, but I won’t introduce them here, and they are not the focus of this article. Let’s take a look at how to use Golang to operate Redis.

1. Install dependency packages

go get -u github.com/go-redis/redis
Copy the code

2. Golang redis connection

// Initialize a client according to the Redis configuration
client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379"./ / redis address
		Password: "".// redis password, if no, leave blank
		DB:       0.// Default database, default is 0
	})
Copy the code

3. Simple examples

  // Initialize a client according to the Redis configuration
	client := redis.NewClient(&redis.Options{
		Addr:     "10.14.181.120:6379"./ / redis address
		Password: "".// redis password, if no, leave blank
		DB:       0.// Default database, default is 0
		PoolSize: 10,})//ping := client.Ping()
	//fmt.Println(ping)

	// Set a key with an expiration time of 0, meaning that it will never expire
	for i := 0; i < 100; i++ {
		err := client.Set("key"+strconv.Itoa(i), "value"+strconv.Itoa(i), time.Hour*1).Err()

		// Check whether the setting is successful
		iferr ! =nil {
			panic(err)
		}
	}
	// Query the cache by key and return two values via the Result function
	// The first represents the value of key, and the second represents the query error information
	val := client.Get("key").Val()
	if val == "" {

		fmt.Println("Value is null")
	}
	fmt.Println("key", val)

	keys := client.Keys("*")

	for e,v := range keys.Val() {
		fmt.Println("-- -- -- -- -- -",e,v)
		//client.Del(v)
	}
Copy the code

Next, we will explain relevant parameters in detail:

Through the example, we know that the connection parameters of Redis are mainly configured through Options. The Options parameter is described in detail below.

Note: The Go-Redis package has its own connection pool, which will automatically maintain redis connections. Therefore, you can create a client, do not query a Redis and close the client.

4. Details about Options parameters

type Options struct {
	// Network type TCP or Unix.
	// The default is TCP.
	Network string
	// Redis address in the format host:port
	Addr string

	// This function is called when a new Redis connection is created
	OnConnect func(*Conn) error

	// Redis password, redis server is not set and can be null.
	Password string
	
	// Redis database, serial number starts from 0, default is 0, you can not set
	DB int

	// Maximum number of retries for redis operation failures. The default value is not retries.
	MaxRetries int
	
	// Minimum retry interval.
	// Default is 8ms; -1 indicates shutdown.
	MinRetryBackoff time.Duration
	
	// Maximum retry interval
	// Default is 512ms; -1 indicates shutdown.
	MaxRetryBackoff time.Duration

	// Redis connection timeout time.
	// The default is 5 seconds.
	DialTimeout time.Duration
	
	// Timeout of socket reading
	// Default is 3 seconds.
	ReadTimeout time.Duration
	
	// Timeout of socket write
	WriteTimeout time.Duration

	// The maximum number of connections in the redis pool.
	The default connection pool size is equal to the number of cpus x 10
	PoolSize int
	
	// The minimum number of free connections in redis connection pool.
	MinIdleConns int
	// The maximum lifetime of redis connections. By default, outdated connections are not closed.
	MaxConnAge time.Duration
	
	// How long does the redis pool wait for a connection to go out after you retrieve it from the pool?
	// The default is to wait ReadTimeout + 1 second.
	PoolTimeout time.Duration
	// How long does the Redis connection pool close an idle connection?
	The default value is 5 minutes. -1 indicates that the configuration item is disabled
	IdleTimeout time.Duration
	// How often to check, idle connection
	The default value is 1 minute. -1 disables idle connection detection
	IdleCheckFrequency time.Duration

	// Set to read-only. If set to true, Redis can only query the cache and cannot update it.
	readOnly bool
}
Copy the code

5. Basic operations

The basic key/value operation of redis refers to the read and write operation for a value whose type is string or number.

Golang Redis:

  • Set – Sets a key value
  • Get – Queries the key value
  • GetSet – Sets the value of a key and returns the old value of the key
  • SetNX – Sets the value of the key if it does not exist
  • MGet – Batch querying key values
  • MSet – Sets key values in batches
  • Incr,IncrBy,IncrByFloat – Increments the value of a key
  • Decr,DecrBy – Decrement the value of a key
  • Del – Deletes keys in batches
  • Expire – Sets the expiration time of the key

1.Set

Set a key value

// The third parameter indicates the expiration time of the key. 0 indicates that the key will not expire.
err := client.Set("key"."value".0).Err()
iferr ! =nil {
	panic(err)
}
Copy the code

2.Get

Query the key value

// The Result function returns two values, the first is the key value and the second is the error message
val, err := client.Get("key").Result()
// Check whether the query error
iferr ! =nil {
	panic(err)
}
fmt.Println("key", val)
Copy the code

3.GetSet

Sets the value of a key and returns the old value of the key

// The Result function returns two values, the first is the key value and the second is the error message
oldVal, err := client.GetSet("key"."new value").Result()

iferr ! =nil {
	panic(err)
}
// Prints the old value of the key
fmt.Println("key", oldVal)
Copy the code

4.SetNX

If the key does not exist, the value of the key is set

// The third parameter indicates the expiration time of the key. 0 indicates that the key will not expire.
err := client.SetNX("key"."value".0).Err()
iferr ! =nil {
	panic(err)
}
Copy the code

5.MGet

Batch querying key values

// The MGet function can pass in any key and return multiple values at once.
The first value is an array, and the second value is an error message
vals, err := client.MGet("key1"."key2"."key3").Result()
iferr ! =nil {
	panic(err)
}
fmt.Println(vals)
Copy the code

6.MSet

Set key values in batches

err := client.MSet("key1"."value1"."key2"."value2"."key3"."value3").Err()
iferr ! =nil {
  panic(err)
}
Copy the code

7.Incr,IncrBy

Incrementing the value of a key

// the Incr function increments one at a time
val, err := client.Incr("key").Result()
iferr ! =nil {
	panic(err)
}
fmt.Println("Latest value", val)

// The IncrBy function, which can specify how much increment each time
val, err := client.IncrBy("key".2).Result()
iferr ! =nil {
	panic(err)
}
fmt.Println("Latest value", val)

// The IncrByFloat function, which can specify how much to increment each time, differs from IncrBy in that the sum is floating point
val, err := client.IncrByFloat("key".2).Result()
iferr ! =nil {
	panic(err)
}
fmt.Println("Latest value", val)
Copy the code

8.Decr,DecrBy

Decrement the value of a key

// Decr decreases by one
val, err := client.Decr("key").Result()
iferr ! =nil {
	panic(err)
}
fmt.Println("Latest value", val)

// DecrBy specifies how much to decrement each time
val, err := client.DecrBy("key".2).Result()
iferr ! =nil {
	panic(err)
}
fmt.Println("Latest value", val)
Copy the code

9.Del

You can delete keys in batches

/ / delete key
client.Del("key")

// Delete multiple keys. The Del function supports deleting multiple keys
err := client.Del("key1"."key2"."key3").Err()
iferr ! =nil {
	panic(err)
}
Copy the code

10.Expire

Set the key expiration time, in seconds

client.Expire("key".3)
Copy the code

6. The hash

If you want the key/value to operate as a hash structure, use the Redis hash type.

Usage Scenario: If you want to cache a piece of user information (including the user ID, user name, and email field) and read partial user information (for example, the user name) or the whole user information, the hash type supports these operations.

The Redis hash operation consists of two or three elements:

  • Key-redis Indicates the unique identifier of the key
  • Field-hash specifies the field name of the data
  • Value – Value. Some operations do not require a value

Go redis hash data

  • HSet – Sets the value of the field based on the key and field fields
  • HGet – Queries the value of the field field based on the key and field fields
  • HGetAll – Queries all fields and values by key
  • HIncrBy – Accumulates values based on key and field fields.
  • HKeys – Returns all field names by key
  • HLen – Queries the number of hash fields by key
  • HMGet – Batch query multiple hash field values based on keys and field names
  • HMSet – Sets hash field values in batches based on key and multiple field names and field values
  • HSetNX – Sets the hash field value if the field does not exist
  • HDel – Deletes hash fields based on key and field names. Hash fields can be deleted in batches
  • HExists – Checks whether the hash field name exists.

Note: No matter what type of data we choose to redis, the operation must have a unique Key, which uniquely identifies the data.

1.HSet

Set the value of the field field based on the key and field fields

// user_1 is the hash key, username is the field name, and tizi365 is the field value
err := client.HSet("user_1"."username"."tizi365").Err()
iferr ! =nil {
	panic(err)
}
Copy the code

2.HGet

Query the value of the field field based on the key and field fields

// user_1 is the hash key and username is the field name
username, err := client.HGet("user_1"."username").Result()
iferr ! =nil {
	panic(err)
}
fmt.Println(username)
Copy the code

3.HGetAll

Query all fields and values by key

// Return all hash fields and values for key=user_1 at once
data, err := client.HGetAll("user_1").Result()
iferr ! =nil {
	panic(err)
}

// Data is a map type, which uses a loop to iterate over output
for field, val := range data {
	fmt.Println(field,val)
}
Copy the code

4.HIncrBy

Accumulates the value of the field based on the key and field fields

// Add the value of the count field at one time by 2. User_1 is the hash key
count, err := client.HIncrBy("user_1"."count".2).Result()
iferr ! =nil {
	panic(err)
}

fmt.Println(count)
Copy the code

5.HKeys

Returns all field names based on key

// keys is a string array
keys, err := client.HKeys("user_1").Result()
iferr ! =nil {
	panic(err)
}

fmt.Println(keys)
Copy the code

6.HLen

Query the number of hash fields based on the key

size, err := client.HLen("key").Result()
iferr ! =nil {
	panic(err)
}

fmt.Println(size)
Copy the code

7.HMGet

Batch query hash field values based on keys and field names

// HMGet supports multiple field names, meaning that multiple field values are returned at once
vals, err := client.HMGet("key"."field1"."field2").Result()
iferr ! =nil {
	panic(err)
}

// Vals is an array
fmt.Println(vals)
Copy the code

8.HMSet

Set hash field values in batches based on keys, field names, and field values

// Initializes multiple field values of hash data
data := make(map[string]interface{})
data["id"] = 1
data["username"] = "tizi"

// Save multiple hash field values at once
err := client.HMSet("key", data).Err()
iferr ! =nil {
	panic(err)
}
Copy the code

9.HSetNX

If the field field does not exist, set the hash field value

err := client.HSetNX("key"."id".100).Err()
iferr ! =nil {
	panic(err)
}
Copy the code

10.HDel

Delete hash fields based on keys and field names. You can delete hash fields in batches

// Delete a field id
client.HDel("key"."id")

// Delete multiple fields
client.HDel("key"."id"."username")
Copy the code

11.HExists

Check whether the hash field name exists.

// Check whether the id field exists
err := client.HExists("key"."id").Err()
iferr ! =nil {
	panic(err)
}
Copy the code