Golang operating Redis database

1. Basic introduction

Second, the installation of Redis

Redis is not recommended for use on Windows, so the official website does not have a Windows version

https://redis.com.cn/download.html

Download, unzip and compile Redis methods:

$ wget https://download.redis.io/releases/redis-6.0.8.tar.gz
$ tar xzf redis-6.0.8.tar.gz
$ cd redis-6.0.8
$ make

Compiled binaries in the srcdirectory. Start Redis:

$ src/redis-server

Use the built-in client to communicate with Redis:

$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

Three, connect and use

3.1 Redis architecture

3.2 Permission login

Redis does not need account password by default, but it can be set:

Modify the configuration in redis.conf and add authentication. (Uncomment the following configuration, then modify the password specified by foobared for you, and restart redis-server to take effect.)

requirepass foobared

Then, when the client connects, enter the auth password to authenticate.

3.3 redis service operation

./src/redis-server							# 开启服务
./src/redis-cli -h 127.0.0.1 -p 6379 shutdown    	# 客户端控制重启

Four, operation commands

See official documentation

  1. Add key-val [set]

  2. View all keys of current redis [keys *]

  3. Get the value corresponding to the key. [get key]

  4. Switch redis database [select index]

  5. How to view the number of key-vals of the current database [dbsize]

  6. Clear the key-val of the current database and clear the key-val of all databases [flushdb flushall]

Redis has 0~15 in-memory databases, which should correspond to the location of the database when using it

Five, Redis CRUD operation

5.1 Redis's five major data types:

The five data types of Redis are: String (string), Hash (hash), List (list), Set (collection) and zset (sorted set: ordered set)

5.2 String-Introduction

String is the most basic type of redis, and a key corresponds to a value.

The string type is binary safe. In addition to ordinary strings, data such as pictures can also be stored.

The maximum string value in redis is 512M

5.2.1 String -CRUD

set [if it exists, it is equivalent to modify, if it does not exist, add it]

get key -> read

del key -> delete

5.2.2 Notes on Strings

  • setex(set with expire) key seconds value

    Set automatic destruction time

  • mset[set one or more key-value pairs at the same time]

  • mget[Get multiple key-vals at the same time]

5.3 Hash-Introduction

5.3.1 Basic introduction

hash and map are similar

Redis hash is a collection of key-value pairs.var user1 map[string]string

Redis hash is a mapping table between field and value of string type. Hash is especially suitable for storing objects .

Basic use: HSET, GSET

5.3.2 Hash-CRUD

hset => save, change

hget => fetch

hgetall => take all

hdel => delete

5.3.3 Details

  • hmset and hmget can set multiple field values ​​and return multiple field values ​​at once

    When setting the name and age for the user, we set it step by step. Using hmset and hmget, you can set multiple filed values ​​and return multiple field values ​​at once.

  • hlen counts how many elements in a hash.

  • hexists key field

    Check whether the given field field exists in the hash table key

5.4 List

The list is a simple list of strings, sorted in the order of insertion. You can add an element to the head (left) or tail (right) of the list . List is essentially a linked list, the elements of the List are ordered, and the values ​​of the elements can be repeated.

5.4.1 List-CRUD

lpush/rpush/ left/right insert

lpop/rpop/lrange pop-up/traverse reading left and right

del delete

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-iSTvd9Va-1608370463401)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20201219104516416.png)]

5.4.2 Matters needing attention

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-l9Cp4mfB-1608370463405) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20201219104633183.png)]

5.5 Set-Introduction

Redis's Set is an unordered collection of string type .

The bottom layer is the HashTable data structure, Set also stores many string elements, string elements are unordered , and the value of the elements cannot be repeated

5.5.1 Set-CRUD

Sadd
smembers [remove all values]
sismember [determines whether the value is a member]
Srem [Delete specified value]

Six, third-party operation redis

6.1 golang 操作 redis

6.1.1 Install dependent packages

Install third-party open source Redis library

  1. Use a third-party open source redis library: github.com/garyburd/redigo/redis

  2. Before using Redis, install the third-party Redis library first, and execute the installation instruction under the GOPATH path: D:\goproject>go get github.com/garyburd/redigo/redis

  3. After the installation is successful, you can see the following packages

6.1.2 Simple Set, Get

package main

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"log"
)

func main() {
    
    
	//连接到redis服务器
	conn, err := redis.Dial(
		"tcp",
		"47.103.203.133:6379",
	)
	defer conn.Close()
	if err != nil {
    
    
		log.Panic("连接失败!", err)
	}

	//写入数据
	_, err = conn.Do("SET", "xwj", "hahaha")
	if err != nil {
    
    
		log.Panic("执行失败!", err)
	}

	//读取数据
	//将读取的数据断言,因为返回的是一个接口
	s, err := redis.String(conn.Do("GET", "xwj"))
	if err != nil {
    
    
		log.Panic("读取失败!", err)
	}
	fmt.Println("内容为:" , s)
}

6.1.3 Read Hash

func main() {
    
    
	c, err := redis.Dial("tcp", "47.103.203.133:6379")
	if err != nil {
    
    
		log.Panic("连接错误!", err)
	}
	defer c.Close()
	_, err = c.Do("Hmset", "people01", "name", "xwj", "age", 18, "job", "it")
	if err != nil {
    
    
		log.Panic("写入错误!", err)
	}
	name, err := redis.String(c.Do("HGet", "people01", "name"))
	if err != nil {
    
    
		log.Panic("读取失败!",err)
	}
	age, err := redis.Int(c.Do("HGet", "people01", "age"))
	if err != nil {
    
    
		log.Panic("读取失败!",err)
	}
	job, err := redis.String(c.Do("HGet", "people01", "job"))
	if err != nil {
    
    
		log.Panic("读取失败!",err)
	}
	fmt.Println(name, strconv.Itoa(age), job)
}

6.1.4 Batch reading

func main() {
    
    
	conn, err := redis.Dial("tcp", "47.103.203.133:6379")
	if err != nil {
    
    
		log.Panic("连接失败!", err)
	}
	defer conn.Close()
	_, err = conn.Do("Hmset", "people02", "name", "zz", "age", 28, "job", "it")
	if err != nil {
    
    
		log.Panic("写入错误!", err)
	}
	//strings可以将多个不同类型的接口值都断言为string数组
	strings, err := redis.Strings(conn.Do("hmget", "people02", "name", "age", "job"))
	if err != nil {
    
    
		log.Panic("读取失败!", err)
	}
	fmt.Println(strings)
}

6.1.5 Set valid time for data

Core code:

_, err = c.Do("expire", "name", 10)

6.1.6 Operating List

Core code

_, err = c.Do("lpush", "heroList", "no1:宋江", 30, "no2:卢俊义", 28)
r, err := redis.String(c.Do("rpop", "heroList"))

Seven, Redis connection pool

To operate Redis through Golang, you can also use Redis link pool, the process is as follows:

  1. Initialize a certain number of links in advance and put them into the link pool

  2. When Go needs to operate Redis, just take out the link directly from the Redis link pool.

  3. This can save the time of temporarily obtaining Redis links, thereby improving efficiency.

  4. Schematic diagram

//定义一个全局的pool
var pool *redis.Pool
//当启动程序时,就初始化连接池
func init() {
    
    
	pool = &redis.Pool{
    
    
		MaxIdle: 8, 		//最大空闲链接数
		MaxActive: 0, 		// 表示和数据库的最大链接数, 0 表示没有限制
		IdleTimeout: 100, 	// 最大空闲时间
		Dial: func() (redis.Conn, error) {
    
     // 初始化链接的代码, 链接哪个ip 的redis
			return redis.Dial("tcp", "47.103.203.133:6379")
		},
	}
}

func main() {
    
    
	//先从pool 取出一个链接
	conn := pool.Get()
	defer conn.Close()

	//同样的使用
	_, err := conn.Do("Set", "name", "汤姆猫~~")
	if err != nil {
    
    
		fmt.Println("conn.Do err=", err)
		return
	}
	//取出
	r, err := redis.String(conn.Do("Get", "name"))
	if err != nil {
    
    
		fmt.Println("conn.Do err=", err)
		return
	}
	fmt.Println("r=", r)
	//如果我们要从pool 取出链接,一定保证链接池是没有关闭
	//defer pool.Close()

	//同样的使用
	conn2 := pool.Get()
	_, err = conn2.Do("Set", "name2", "汤姆猫~~2")
	if err != nil {
    
    
		fmt.Println("conn.Do err~~~~=", err)
		return
	}
	//取出
	r2, err := redis.String(conn2.Do("Get", "name2"))
	if err != nil {
    
    
		fmt.Println("conn.Do err=", err)
		return
	}
	fmt.Println("r=", r2)
	//fmt.Println("conn2=", conn2)
}

Tips

1.DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authenticatio n password is requested to clients.

Need to modify the configuration file redis.conf

Because I put it on the server, and the default configuration is local and the protected mode is turned on, so modify it

The bind 127.0.0.1comment out

Set protected-mode to no

2. NOAUTH Authentication required.

If a password is set, then you need to modify the parameters of the Dial connection

Enter the Dial function, set the dialOptions field, and password as the password.

func Dial(network, address string, options ...DialOption) (Conn, error) {
	do := dialOptions{
		dialer: &net.Dialer{
			KeepAlive: time.Minute * 5,
		},
		password: "xxxxxx",   #你的密码
	}
	for _, option := range options {
		option.f(&do)
	}
	if do.dial == nil {
		do.dial = do.dialer.Dial
	}

	netConn, err := do.dial(network, address)
	if err != nil {
		return nil, err
	}
	.......
}

All fields of the dialOptions structure:

type dialOptions struct {
	readTimeout  time.Duration
	writeTimeout time.Duration
	dialer       *net.Dialer
	dial         func(network, addr string) (net.Conn, error)
	db           int
	password     string
	useTLS       bool
	skipVerify   bool
	tlsConfig    *tls.Config
}

After modifying the source code in this way, it can be used normally.

Guess you like

Origin blog.csdn.net/weixin_43988498/article/details/111407971