Basic introduction to Redis
Redis installation
Basic principle diagram of Redis operation
Redis installation and basic use
Redis startup:
Redis operation instruction list
Basic use of Redis:
Note: After Redis is installed, there are 16 databases by default. The initial default is to use library 0, the numbers are 0 ... 15
1. Add key-val [set]
2. View all keys of the current redis [keys *]
3. Get the value corresponding to key. [Get key]
4. Switch the redis database [select index]
5. How to check the number of key-val in the current database [dbsize]
6. Clear the key-val of the current database and the key-val of all databases [flushdb flushall]
Redis Crud operation
Five data types of Redis:
The five major data types of Redis are: String, Hash, List, Set, and zset (sorted set: sorted set)
String-Introduction
String is the most basic type of redis, one key corresponds to one value.
The string type is binary safe. In addition to ordinary character strings, data such as pictures can also be stored.
The maximum value of the string value in redis is 512M
For example, store an address information: address Beijing Tiananmen
Description:
key : address
value: Beijing Tiananmen Square
String -CRUD
Give an example to illustrate the CRUD operation of Redis String.
set [If it exists, it is equivalent to modification, if it does not exist, then add] / get / del
String (string)-usage details and precautions
setex (set with expire) key seconds value
mset [set one or more key-value pairs simultaneously]
mget [Get multiple key-vals simultaneously]
Hash (Hash, similar to Map in golang)-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 type string. Hash is especially suitable for storing objects.
For example, store a User information: (user1)
user1 name "smith" age 30 job "golang coder"
Description:
key : user1
name Zhang San and age 30 are two pairs of field-value
Hash (hash, similar to Map in golang)-CRUD
Give an example to illustrate the basic operations of Redis Hash CRUD. Hset / hget / hgetall / hdel
Demonstrate the case of adding user information (name, age)
Hash-use details and precautions
When setting the name and age for the user, we set it up step by step. Using hmset and hmget can set multiple filed values and return multiple field values at once.
hlen counts several elements of a hash.
hexists key field
Check whether the given field field exists in the hash table key
List-Introduction
The list is a simple list of strings, sorted in 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 List are ordered and the values of the elements can be repeated. For example, store multiple address information:
city Beijing Beijing Tianjin Shanghai Explanation:
key : city
Beijing, Tianjin, and Shanghai are three elements
Getting started
List-CRUD
Illustrate the CRUD operation of Redis List.
lpush / rpush / lrange / lpop / rpop / del /
Explanation:
List drawing helps students understand (L can be imagined as a pipe.)
Demo
List-use details and precautions
Set-Introduction
Redis's Set is an unordered set of type string.
The bottom layer is the HashTable data structure. Set also stores many string elements. The string elements are unordered, and the values of the elements cannot be repeated
For example, store multiple mailing list information:
Description:
key : email
[email protected] [email protected] are two elements
redis>sadd email xx xxx
Set-CRUD
Illustrate the CRUD operation of Redis Set. Sadd
smembers [get all the values] sismember [judging whether the value is a member] srem [delete the specified value]
Demonstrate the case of adding multiple email messages
Red Gol Redis
Install a third-party open source Redis library
1) Use a third-party open source redis library: github.com/garyburd/redigo/redis
2) Before using Redis, first install a third-party Redis library and execute the installation instructions in the GOPATH path: D: \ goproject> go get github.com/garyburd/redigo/redis
3) After the installation is successful, you can see the following packages
Special note: Before installing the Redis library, make sure that Git has been installed and configured, because the Redis library is downloaded and installed from github, you need to use Git. If you have not installed and configured Git, please refer to: How to Install and Configure Git
Set / Get interface
Explanation: Add and obtain key-value through Golang [such as name-tom ~]
package main import ( "fmt" "github.com/garyburd/redigo/redis" // Introduce redis package ) func main() { // Write data to and read data from 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 to redis via go [key-val] _, err = conn.Do("Set", "name", "tomjerry 猫猫") if err != nil { fmt.Println("set err=", err)
return } // 3. Read data string to redis through go [key-val] r, err := redis.String(conn.Do("Get", "name")) if err != nil { fmt.Println("set err=", err)
return } // because return r is interface {} // Because the value corresponding to name is string, we need to convert //nameString := r.(string) fmt.Println("操作 ok ", r) }
Operation Hash
Description: Operate Hash data type on Redis through Golang
For the hash data structure, field-val is a code to put and read:
package main import ( "fmt" "github.com/garyburd/redigo/redis" // Introduce redis package ) func main() { // Write data to and read data from 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 to redis via go [key-val] _, 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 from redis through go r1, 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 return r is interface {} // Because the value corresponding to name is string, we need to convert //nameString := r.(string) fmt.Printf("操作 ok r1=%v r2=%v \n", r1, r2) }
For hash data structures, field-val is to put and read in batches
package main import ( "fmt" "github.com/garyburd/redigo/redis" // Introduce redis package ) func main() { // Write data to and read data from 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 to redis via go [key-val] _, err = conn.Do("HMSet", "user02", "name", "john", "age", 19) if err != nil { fmt.Println("HMSet err=", err) return } // 3. Read data from redis through go r, err := redis.Strings(conn.Do("HMGet","user02", "name", "age")) if err != nil { fmt.Println("hget err=", err) return } for i, v := range r { fmt.Printf("r[%d]=%s\n", i, v) } }
Batch Set / Get data
Note: Through Golang operation on Redis, one operation can set / get multiple key-val data core codes:
_, err = c.Do ("MSet", "name", "Silicon Valley", "address", "Beijing Changping ~")
r, err := redis.Strings(c.Do("MGet", "name", "address"))
for _, v := range r { fmt.Println(v)
}
Set valid time for data
Explanation: Use Golang to operate Redis, and set the effective time for the key-value core code:
// Set the valid time for name data to 10s
_, err = c.Do("expire", "name", 10)
Operation List
Description: The core code for operating the Redis List data type through Golang:
_, err = c.Do("lpush", "heroList", "no1:宋江", 30, "no2:卢俊义", 28) r, err := redis.String(c.Do("rpop", "heroList"))
Redis link pool
Note: The operation of Redis through Golang can also be through the 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 the link directly from the Redis link pool.
3) This can save time to temporarily obtain Redis links, thereby improving efficiency.
4) Schematic diagram
package main import ( "fmt" "Github.com/garyburd/redigo/redis" ) // Define a global pool was pool * redis.Pool // When the program is started, the connection pool is initialized func init() { pool = &redis.Pool{ MaxIdle: 8, // Maximum number of idle links MaxActive: 0, // means the maximum number of links to the database, 0 means no limit IdleTimeout: 100, // maximum idle time Dial: func () (redis.Conn, error) {// The code to initialize the link, which ip of redis to link return redis.Dial("tcp", "localhost:6379") }, } } func main() { // First take a link from the pool conn := pool.Get() defer conn.Close() _, err := conn.Do("Set", "name", "汤姆猫~~") if err != nil { fmt.Println("conn.Do err=", err) return } //take out r, err := redis.String(conn.Do("Get", "name")) if err != nil { fmt.Println("conn.Do err=", err) return } fmt.Println("r=", r) // If we want to remove the link from the pool, we must ensure that the link pool is not closed //pool.Close() conn2 := pool.Get() _, err = conn2.Do("Set", "name2", "汤姆猫~~2") if err != nil { fmt.Println("conn.Do err~~~~=", err) return } //take out 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) }