Go language series redis

Time:2020-8-13

Use of redis

Basic introduction to redis

  1. Redis is a NoSQL database, not a traditional relational database official website https://redis.io/ And http://www.redis.cn/

  2. Redis:REmote DIctionary Server (remote dictionary server). The performance of redis is very high. A single machine can reach 15W QPS. It is usually suitable for caching and persistence.

  3. It is a fully open source, free, high-performance (key / value) distributed memory database. NoSQL database based on memory running and supporting persistence is one of the most popular nosq | databases, also known as data structure server

Redis installation

Link: https://pan.baidu.com/s/1QTYTKepSGZA93KCA76eatQ

Extraction code: au10

After downloading, you can directly unzip the redis server-side program (redis)- server.exe )And client program (redis)- cli.exe ), you can run it directly by double clicking, and you do not need to install it.

Basic schematic diagram of redis operation

Installation and basic use of redis

The start of redis


Start the redis server-side program (redis- server.exe ), double click to run

List of redis operation instructions

Basic use of redis

Note: after redis is installed, there are 16 databases by default, and No. 0 database is used by default, with the number of.. 15

  1. Add key Val [set]

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

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

  4. Switch redis database [select index]

  5. How to view the key Val quantity of the current database [dbsize]

  6. Empty key Val of current database and key Val of all databases [fiushdb flushall]

The crud operation of redis

Five data types of redis

Redis has five data types: string, hash, list, set and Zset

String – Introduction

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

String is a binary safe type. In addition to ordinary strings, it can also store images and other data.

The maximum string value in redis is 512M

For example, store an address information:

Address Tiananmen, Beijing

explain:

key : address

Value: Tiananmen, Beijing

127.0.0.1:6379> set address beijing
OK
127.0.0.1:6379> get address
"beijing"

String – CRUD

Examples of redis string string crud operation

Set [if it exists, it is equivalent to modification; if it does not exist, it is added] / get / del

127.0.0.1:6379> del address
(integer) 1
127.0.0.1:6379> get address
(nil)

String – usage details and precautions

Setex (set with expire) key seconds

127.0.0.1:6379> SETEX mess01 10 hello,you
OK
127.0.0.1:6379> get mess01
"hello,you"
127.0.0.1:6379> get mess01
"hello,you"
127.0.0.1:6379> get mess01
(nil)

Mset [set one or more key value pairs at the same time]

Mget [get multiple key Val at the same time]

127.0.0.1:6379> MSET worker01 tom worker02 scott
OK
127.0.0.1:6379> get worker02
"scott"
127.0.0.1:6379> MGET worker01 worker02
1) "tom"
2) "scott"

Hash (hash, similar to map in golang) – Introduction

Basic introduction

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

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

For example, store a user information: (user1)

userl name “smith” age 30 job “golang coder”

explain:

key : userl

Name Zhang San and age 30 are two pairs of field values

Hash (hash, similar to map in golang) – CRUD

Examples are given to illustrate the basic operation of redis hash crud

hset/hget/hgetall/hdel

Demonstrate the case of adding user information (name, age)

127.0.0.1:6379> HGETALL user1
1) "name"
2) "smith"
3) "age"
4) "30"
5) "job"
6) "golang coder"

Hash details and precautions

When setting the name and age for the user, we are setting step by step. Using hmset and hmget, you can set the values of multiple fileds and return the values of multiple fields at one time.

HLEN statistics a hash has several elements

Hexests key field check whether the given field exists in the hash table key

127.0.0.1:6379> hmset user2 name jerry age 110 job "java coder"
OK
127.0.0.1:6379> hmget user2 name age job
1) "jerry"
2) "110"
3) "java coder"
127.0.0.1:6379> hlen user2
(integer) 3
127.0.0.1:6379> HEXISTS user2 name
(integer) 1
127.0.0.1:6379> hexists user2 name2
(integer) 0

Hash practice

For example, store a student information:

Stu1 name Zhang San age 30 score 80 address Beijing

explain:

Through the relevant instructions, complete the crud operation of the student

List – Introduction

A list is a simple list of strings, sorted in insertion order. You can add an element to the head (left) or tail (right) of the list.

The essence of list is a linked list. The elements of list are ordered and the values of elements can be repeated

For example, store multiple address information:

City Beijing Tianjin Shanghai

explain:

key:city

Beijing, Tianjin and Shanghai are three elements

Introductory cases

127.0.0.1:6379> LPUSH city berjing shanghai tianjing
(integer) 3
127.0.0.1:6379> lrange city 0 -1
1) "tianjing"
2) "shanghai"
3) "berjing"

List CRUD

Examples are given to illustrate the crud operation of redis’s list.

lpush/rpush/lrange/lpop/rpop/del/

explain

List drawing helps understand (think of list as a pipe)

Herolist’s demonstration

127.0.0.1:6379> lpush herolist aaa bbb ccc
(integer) 3
127.0.0.1:6379> LRANGE herolist 0 -1
1) "ccc"
2) "bbb"
3) "aaa"
127.0.0.1:6379> rpush herolist ddd eee
(integer) 5
127.0.0.1:6379> lrange herolist 0 -1
1) "ccc"
2) "bbb"
3) "aaa"
4) "ddd"
5) "eee"
127.0.0.1:6379>  rpop herolist
"eee"
127.0.0.1:6379> lrange herolist 0 -1
1) "ccc"
2) "bbb"
3) "aaa"
4) "ddd"
127.0.0.1:6379> del herolist
(integer) 1
127.0.0.1:6379> lrange herolist 0 -1
(empty list or set)

List – usage details and precautions

(1) Lindex, get the elements by index index index (from left to right, numbering from 0.)

(2) LLEN key

Returns the length of the list key. If the key does not exist, the key is interpreted as an empty list and returns 0

(3) Other descriptions of list

List data can be inserted and added from left or right;

If all the values are removed, the corresponding key disappears.

Set – Introduction

Redis’s set is an unordered set of string type.

The underlying layer is the hashtable data structure. Set also stores many string elements. String elements are unordered and the values of elements cannot be repeated

For example, store multiple mailing list information:

email [email protected] [email protected]

explain:

key : email

[email protected] [email protected] There are two elements

127.0.0.1:6379> sadd emails [email protected] [email protected]
(integer) 2
127.0.0.1:6379> SMEMBERS emails
1) "[email protected]"
2) "[email protected]"
127.0.0.1:6379> sadd emails [email protected] [email protected]
(integer) 2
127.0.0.1:6379> SMEMBERS emails
1) "[email protected]"
2) "[email protected]"
3) "[email protected]"
4) "[email protected]"
127.0.0.1:6379> sadd emails [email protected] 
(integer) 0
127.0.0.1:6379> SMEMBERS emails
1) "[email protected]"
2) "[email protected]"
3) "[email protected]"
4) "[email protected]"

Set CRUD

Examples are given to illustrate the crud operation of redis’s set

sadd

Smembers [extract all values]

Sismember [judge whether the value is a member]

SREM [delete specified value]

Demonstrate the case of adding multiple email messages

127.0.0.1:6379> SISMEMBER emails [email protected]
(integer) 1
127.0.0.1:6379> SISMEMBER emails [email protected]
(integer) 0
127.0.0.1:6379> srem emails [email protected]
(integer) 1
127.0.0.1:6379> SMEMBERS emails
1) "[email protected]"
2) "[email protected]"
3) "[email protected]"

Set exercise

For example, store a product information:

It includes the trade name, price and date of production.

Complete the corresponding crud operation

Golang operation redis

Install the third party open source redis Library

1) Using a third-party open source redis Library: github.com/garyburd/redigo/redis

2) Before using redis, install the third-party redis library and execute the installation instructions in gopath path

​ E:\gostudent>go get github.com/garyburd/redigo/redis

3) After the installation is successful, you can see the following package

Special note: before installing redis library, make sure git has been installed and configured, because redis library is downloaded and installed from GitHub, and git needs to be used.

E:\gostudent>go get github.com/garyburd/redigo/redis
\# cd .; git clone -- https://github.com/garyburd/redigo E:\gostudent\src\github.com\garyburd\redigo
Cloning into 'E:\gostudent\src\github.com\garyburd\redigo'...
fatal: unable to access 'https://github.com/garyburd/redigo/': Failed to connect to github.com port 443: Timed out
package github.com/garyburd/redigo/redis: exit status 128

Just do it a few more times. We all know why

Set / get interface

Note: add and obtain key value [such as name Tom ~] through golang

package main

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

func main() {
  //Write and read data to redis through go
  //1. Link to redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer  conn.Close () // close

  //2. Write data stringf [Key Val] to redis through go
  A kind of , err =  conn.Do ("set", "name", "tomjerry"
  if err != nil {
   fmt.Println("set err = ", err)
   return
  }
  
  //3. Read the data string [Key Val] from redis through go
  r, err := redis.String(conn.Do("Get","name"))
  if err != nil {
   fmt.Println("set err = ", err)
   return
  }
  //Because the return R is interface {}
  //Because the value of name is string, we need to convert it
  //nameString := r.(string)
  fmt.Println ("operation OK", R)
}
//Operation OK tomjerry

Operation hash

Description: hash data type is operated on redis through golang

For hash data structures, field Val is put and read one by one

code:

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

func main() {
  //Write and read data to redis through go
  //1. Link to redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer  conn.Close () // close

  //2. Write data string [key - Val] to redis through go
  _,err = conn.Do("HSet","user01","name","john")
  if err != nil {
   fmt.Println("hset err = ", err)
   return
  }
  _, err = conn.Do("HSet","user01","age",18)
  if err != nil {
   fmt.Println("hset err =", err)
   return
  }

  //3. Read data to redis through go
  r, err := redis.String(conn.Do("HGet","user01","name"))
  if err != nil {
   fmt.Println("hget err = ", err)
   return
  }

  r2, err := redis.Int(conn.Do("HGet","user01","age"))
  if err != nil{
   fmt.Println("hget err =", err)
   return
  }

  //Because the return R is interface {}
  //Because the value of name is string, it needs to be converted
  //nameString := r.(string)

  fmt.Printf ("operation OK R1 =% v R2 =% v / N", R, R2)

}
//Operation OK R1 = John R2 = 18

For hash data structure, field Val is batch put and read

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

func main() {
  //Write and read data to redis through go
  //1. Link to redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer  conn.Close () // close

  //2. Write data string [key - Val] to redis through go
  _,err = conn.Do("HMSet","user02","name","john","age",19)
  if err != nil {
   fmt.Println("HMSet err = ", err)
   return
  }

  //3. Read data to redis through go
  r, err := redis.Strings(conn.Do("HMGet","user02","name","age"))
  if err != nil {
   fmt.Println("HMGet err = ", err)
   return
  }
  for i, v := range r {
   fmt.Printf("r[%d] = %s\n", i, v)
  }
}
//r[0] = john
//r[1] = 19

Batch set / get data

Note: multiple key Val data can be set / get in one operation through the operation of redis by golang

Core code:

A kind of , err = C.do ("Mset", "name", "zisefeizhu", "address", "China")
r, err := redis.Strings(c.Do("MGet", 'name", " address"))
for. ,V := range r {
	fmt.Println(v)
}

Set valid time for data

Note: through the operation of redis by golang, set the effective time for the key value

Core code:

//Set the valid time of name data to 10s

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

Operation list

Note: list data type is operated on redis through golang

Core code:

A kind of , err = C.do ("lpush", "herolist", "No1: Songjiang", 30, "NO2: Lu Junyi", 28)
r, err := redis.String(c.Do("rpop", "heroList"))

Redis link pool

Note: redis can be operated through golang or 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,*Take out the link directly from the redis link pool*That’s fine.

3) in this way, temporary work can be saved*Get redis link*To improve efficiency

4) schematic diagram

*Link pool use cases*

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

//Define a global pool
var pool *redis.Pool

//When the program is started, the link pool is initialized
func init()  {
  pool = &redis.Pool{
   Dial: func() ( redis.Conn , error) {// initializes the link code, which IP address is linked to redis
     return redis.Dial("tcp","localhost:6379")
   },
   Maxidle: 8, // maximum number of free links
   Maxactive: 0, // indicates the maximum number of links to the database, and 0 indicates that there is no limit
   Idletimeout: 100, // maximum idle time
  }
}

func main()  {
  //Take a link from the pool first
  conn := pool.Get()
  defer conn.Close()

  A kind of , err :=  conn.Do ("set", "name", "Tom cat ~")
  if err != nil {
   fmt.Println("conn.Do err=", err)
   return
  }

  //Remove
  r, err := redis.String(conn.Do("Get","name"))
  if err != nil {
   fmt.Println("conn.Do err =", err)
   return
  }

  fmt.Println("r =", r)

  //If you want to remove links from the pool, make sure that the link pool is not closed
  // pool.Close()
  conn2 := pool.Get()

  A kind of , err = conn2. Do ("set", "Name2", "Tomcat ~ 2")
  if err != nil {
   fmt.Println("conn.Do err ~~=", err)
   return
  }

  //Remove
  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)
}
//R = Tom Cat~
//R = Tom Cat~2

Another example

var pool *redis.Pool

func init() {
  pool = &redis.Pool{
   MaxIdle:   8,
   MaxActive:  0,
   IdleTimeout: 100,
   Dial: func() (redis.Conn, error) {
     return redis.Dial("tcp", "localhost:6379")
   },
  }
}

func main() {
  conn := pool.Get()
  defer conn.Close()

  _, err1 := conn.Do("HMSet", "user1", "name", "beijing", "address", "beijing")
  if err1 != nil {
   fmt.Println("HMSet err=", err1)
   return
  }
  _, err3 := conn.Do("HMSet", "user2", "name", "wuhan", "address", "wuhan")
  if err3 != nil {
   fmt.Println("HMSet err=", err3)
   return
  }

  //Read data to redis, and the returned R is an empty interface
  r, err2 := redis.Strings(conn.Do("HMGet", "user1", "name", "address"))
  if err2 != nil {
   fmt.Println("HMGet err=", err2)
   return
  }
  for i, v := range r {
   fmt.Printf("r[%d]=%v\n", i, v)
  }
}
//r[0]=beijing
//r[1]=beijing

Recommended Today

CentOS 7 starts and stops using systemctl configuration management service

The servers of our company are basically CentOS 7. X system, and the services installed through the system source can be accessed through thesystemctl start XXX.serviceBut some components can only be installed to the server by decompressing the tar package because of various irresistible factors. Each time you start, you need to execute specific commands […]