go language series -redis

Redis use

Redis basic introduction

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

  2. Redis: REmote DIctionary Server (remote dictionary server), Redis very high performance, stand-alone can be achieved 15w qps, usually suitable for caching, it can also be persistent.

  3. Is completely open source free, high-performance (key / value) distributed in-memory database, based on memory to run and support the persistence of NoSQL databases, the most popular NoSq | one database server is also known as a data structure

Redis installation

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

Extraction code: au10

There is direct decompression after downloading Redis server-side programs (redis- server.exe) and client (redis-cli.exe), simply double-click to run, you do not need to be installed.

The basic principle of the operation of FIG Redis

Installation and basic use of Redis

Redis start


Redis server-side program starts in (redis-server.exe), simply double-click to run

Redis operation instruction list

The basic use of Redis

Description: After Redis installed, the default database there are 16 initial default library using a No. 0, No. ..15

  1. Add key-val [set]

  2. View all current redis key [keys *]

  3. Obtaining a value corresponding key. [Get key]

  4. Database switching redis [select index]

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

  6. Clear the current database key-val and emptying all databases key-val [fiushdb flushall]

Redis of Crud operations

Five types of data Redis

Five Redis data types are: String (String), Hash (hash), List (list), Set (collection) and zset (sorted set: an ordered collection)

String (String) - Introduction

redis string is the most basic type, a key corresponding to a value.

The string type is binary safe. In addition to the normal string, you can also store pictures and other data.

redis string value is the maximum 512M

For example, a store address information:

address Beijing Tiananmen Square

Description:

key : address

value: Beijing Tiananmen Square

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

String (String) -CRUD

String CRUD operations illustrate the Redis string.

set [If there is equivalent modifications, there is added] / get / del

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

String (String) - Use details and notes

setex (set with expire) second key value

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 [simultaneously providing one or more key-value pairs]

mget [simultaneously acquiring a plurality of key-val]

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 golang in the Map) - Introduction

Basic introduction

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

Redis hash field is a string type and the value of the mapping table, hash is particularly suited for storing objects.

For example, a User information is stored: (user1)

userl name "smith" age 30 job "golang coder"

Description:

key : userl

Joe Smith name and age 30 is two pairs of field-value

Hash (hash, similar golang in the Map) -CRUD

Illustrates the basic CRUD operations of the Redis Hash.

hset/hget/hgetall/hdel

Add user information of case presentations (name, age)

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

Hash- usage details and notes

When a user name and a set Age, we are in front of a step - by step set up, use and hmget hmset set value may be a plurality of disposable filed and return values ​​of the plurality of field.

hlen a hash statistics there are several elements

hexists key field to view the hash table key, the presence or absence of a given domain field

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 Exercises

For example, a store information Student:

stu1 name Joe Smith age 30 score 80 address Beijing

Description:

Through the relevant instructions to complete the operation of the Student crud

List (list) - Introduction

List is a simple list of strings, sort insertion order. You can add an element to the head of the list (on the left) or tails (to the right).

List is essentially a linked list, List elements are ordered, the value of the element can be repeated.

Examples storing a plurality of address information:

Beijing, Tianjin, Shanghai city

Description:

key:city

Beijing Tianjin Shanghai are the three elements

Getting Case

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 (list) -CRUD

List of illustrated Redis CRUD operations.

lpush / rpush / lrange / lpop / RPOP / of the /

Explanation

List of drawing help understand (List can be thought of as a pipe)

the presentation of herolist

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 notes

(1) lindex, obtained according to the indexing subscript element (from left to right, numbered from zero.)

(2) FILL key

Key returns the length of the list, if the key does not exist, then the key is interpreted as an empty list, return 0

Additional notes (3) List of

List data, can be inserted from the left or right is added;

If the values ​​are all removed, the corresponding button will disappear.

Set (collection) - Introduction

Redis is a string Set the type of unordered collection.

The underlying data structure is HashTable, Set number string element is stored, a random string element, and the value of the element can not be duplicated

For example, store multiple mailing list information:

email [email protected] [email protected]

Description:

key : email

[email protected] [email protected] that 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 (collection) - CRUD

Set of CRUD operations illustrate the Redis.

sadd

smembers [Remove all values]

sismember [determines whether the value is a member]

[Delete the specified value] srem

Demos add multiple e-mail message case

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 Exercises

For example, a store product information:

Including product name, price, date of production.

Corresponding to the operation completion crud

Golang 操作 Redis

Install a third-party open source libraries Redis

1) Use of third party open source libraries redis: github.com/garyburd/redigo/redis

2) before use Redis, Redis to install third-party libraries, perform the installation instructions at GOPATH path:

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

3) After successful installation, see the following packages

Special Note: Before installing Redis database, ensure that you have installed and configured Git, because Redis is download and install the library from github, need to use Git.

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

Execute it several times like the reason we know everything

Set / Get Interface

Description: By adding Golang key-value acquisition and such name-tom ~ []

package main

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

func main() {
  //通过go向redis写入数据和读取数据
  //1. 链接到redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer conn.Close() //关闭...

  //2. 通过go向redis写入数据strinf [key-val]
  _, err = conn.Do("Set", "name","tomjerry 猫猫")
  if err != nil {
   fmt.Println("set err = ", err)
   return
  }
  
  //3. 通过go 向redis读取数据string [key-val]
  r, err := redis.String(conn.Do("Get","name"))
  if err != nil {
   fmt.Println("set err = ", err)
   return
  }
  //因为返回r是interface{}
  //因为name对应的值是string ,因此我们需要转换
  //nameString := r.(string)
  fmt.Println("操作OK", r)
}
//操作OK tomjerry 猫猫

Hash operation

Description: Hash operation on the data type Golang Redis

To hash data structure, field-val is read one by one and placed

Code:

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

func main() {
  //通过go向redis写入数据和读取数据
  //1. 链接到redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer conn.Close() //关闭...

  //2. 通过go向redis写入数据string [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. 通过go向redis读取数据
  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
  }

  //因为返回r是interface{}
  //因为name对应的值是string,因此需要转换
  //nameString := r.(string)

  fmt.Printf("操作ok r1 = %v r2 = %v\n", r, r2)

}
//操作ok r1 = john r2 = 18

对hash数据结构,field-val是批量放入和读取

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

func main() {
  //通过go向redis写入数据和读取数据
  //1. 链接到redis
  conn, err := redis.Dial("tcp", "127.0.0.1:6379")
  if err != nil {
   fmt.Println("redis.Dial err =", err)
   return
  }
  defer conn.Close() //关闭...

  //2. 通过go向redis写入数据string [key - val]
  _,err = conn.Do("HMSet","user02","name","john","age",19)
  if err != nil {
   fmt.Println("HMSet err = ", err)
   return
  }

  //3. 通过go向redis读取数据
  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 the data

Description: By Golang Redis of operation, one operation can Set / Get the plurality of data key-val

Core code:

_, err = c.Do("MSet", "name",”zisefeizhu","address", "中国")
r, err := redis.Strings(c.Do("MGet", 'name", " address"))
for. ,V := range r {
	fmt.Println(v)
}

Set the data valid time

Description: By Golang Redis of operation, to the key-value setting effective time

Core code:

// set to the name data valid for 10s

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

Operation List

Description: List by Golang operation data type Redis

Core code:

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

Redis connection pooling

Description: By Golang Redis of operation, the link can also Redis pool, process is as follows:

1) prior to initialize a certain number of links, link into pool

2) When the operations required Redis Go, * * remove the link from the pool Redis link to.

3) This saves the temporary * Get links * Redis time, thus improving efficiency.

4) Schematic

* Link pool use cases *

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

//定义一个全局的pool
var pool *redis.Pool

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

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 取出链接,一定要保证链接池是没有关闭
  // 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)
}
//r = 汤姆猫~
//r = 汤姆猫~2

再来一例

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
  }

  //向redis读取数据,返回的r是个空接口
  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

Guess you like

Origin www.cnblogs.com/zisefeizhu/p/12655907.html