GO installation and operation of redis

Keywords: Programming Redis github Database Windows

1. Install redis and start redis service

  • windows installation tutorial:
  • linux Installation Tutorial:

2. Use go get to download redis extension package

Execute the installation command at the cmd command line:

go get github.com/garyburd/redigo/redis

After installation, the source package will be placed in the $GOPATHF/src/github.com directory. My GOPATH is F:\godev, so my directory after installation is as follows:

3. Use go to operate redis

package main

// 1. Import redis package
import (
	"fmt"
	"time"

	"github.com/garyburd/redigo/redis"
)

func main() {
	// Connection timeout
	optionTimeout := redis.DialConnectTimeout(time.Second * 10)

	// Which database to connect to is the 0 database by default
	optionDb := redis.DialDatabase(1)

	// Password for the connection (if set)
	optionPwd := redis.DialPassword("123456")

	// 2. The first parameter to connect to the redis service is network type redis is tcp/ip protocol, the second parameter is redisHost:redisPort the third parameter is connection configuration
	conn, err := redis.Dial("tcp", "127.0.0.1:6379", optionTimeout, optionDb, optionPwd)
	if err != nil {
		fmt.Println("conn redis server err,", err.Error())
		return
	}

	// 3. Close the redis connection after processing
	defer conn.Close()

	// 4. Operation of redis set command the Do method sends the redis operation command to return the operation result
	replyRes, err := conn.Do("set", "username", "A little class")

	// Use the method in redis package to parse the returned results
	str, _ := redis.String(replyRes, err)
	fmt.Println(str) //OK

	// 5.redis get command operation
	replyRes, err = conn.Do("get", "username")

	// Use the method in redis package to parse the returned results
	str, _ = redis.String(replyRes, err)
	fmt.Println(str) //A little class

	// 6.redis list command operation
	replyRes, err = conn.Do("lpush", "msg-list", "msg1")
	str, _ = redis.String(replyRes, err)
	fmt.Println(str) //Empty string

	replyRes, err = conn.Do("lpop", "msg-list")
	str, _ = redis.String(replyRes, err)
	fmt.Println(str) //msg1
}

Use Do method to execute all the commands of redis. The returned result is the result after the command is executed. Pay attention to the method corresponding to redis package to parse the returned result!

Posted by jason102178 on Mon, 16 Dec 2019 06:25:12 -0800