go-redis

repeat

Redis basic introduction

redis is nosql database, not a traditional database, high performance, suitable for caching is also suitable for making persistent ,, completely free open source, high-performance, distributed memory to run memory-based database ,, and ,, most persistent support one popular nosql database, also known as data structure server.

repeat

Two installation, compressed package type, and the setup file type, relatively simple,
if it is compressed type: redis.server start service window is not closed, redis.client, client operation data;
slightly

Redis operation instruction list

Instructions [http://redisdoc.com/]

redis basic use:

Description: After Redis installed, the default database there are 16 initial default library using a No. 0, No. 0 ... 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 [flushdb flushall]

Redis of Crud operations

Five Redis data types:

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, pictures and other data can also be stored in redis string value is the maximum 512M

举例,存放一个地址信息:
address 北京天安门
说明 :
key : address
value: 北京天安门

String(字符串) -CRUD
举例说明 Redis 的 String 字符串的 CRUD 操作.
set[如果存在就相当于修改,不存在就是添加]/get/del

String (String) - Use details and notes

setex (set with expire) second key value (after 10s, the data disappears)
MSET [simultaneously providing one or more key-value pairs]
mget [simultaneously acquiring a plurality of key-val]

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

Basic introduction to
Redis hash is a collection of key-value pairs. Map user1 var [String] String
the Redis is the hash value and a type field mapping table string, hash is particularly suitable for storing

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

user1 name "smith" age 30 job "golang coder"
说明 :
key : user1
name 张三 和 age 30 就是两对 field-value

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

Illustrates the basic CRUD operations of the Redis Hash.
HSET / hget / hgetall / HDEL
case add user presentation information (name, age)

Hash- usage details and notes

When a user name and Age provided, arranged in front of us is step by step, and using hmset hmget can be provided disposable
set values and return values of the plurality of filed of a plurality of field.
hlen a hash statistics has several elements.
hexists key field
to view the hash table key, the presence or absence of a given domain field

List (list) - Introduction

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

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

举例, 存放多个地址信息:
city 北京 天津 上海
说明 :
key : city
北京 天津 上海 就是三个元素

List (list) -CRUD (similar pipeline)

List of illustrated Redis CRUD operations.
lpush / rpush / lrange / lpop / rpop / del /

List- usage details and notes

1) Get the element by index
2) llen key length acquired, if the key does not exist, a key is interpreted as empty list, return 0
. 3) List may plug the left and right plug
4) if all removed, the corresponding key disappeared

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

举例,存放多个邮件列表信息:
email [email protected] [email protected]
说明 :
key : [email protected] [email protected] 就是二个元素
redis>sadd email xx xxx

Set (collection) - CRUD

Set of CRUD operations illustrate the Redis.

sadd
smembers[取出所有值]
sismember[判断值是否是成员]
srem [删除指定值]

The above basic operation command

127.0.0.1:6379> dbsize
(integer) 4
127.0.0.1:6379> del name
(integer) 1
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> setx name 10 hello,go
(error) ERR unknown command 'setx'
127.0.0.1:6379> setex name 10 hello,go
OK
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> setex name 10 hello,go
OK
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
"hello,go"
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> get name
(nil)
127.0.0.1:6379> mset name a name2 b
OK
127.0.0.1:6379> get name
"a"
127.0.0.1:6379> get name2
"b"
127.0.0.1:6379> dbsize
(integer) 4
127.0.0.1:6379> get user01
(error) WRONGTYPE Operation against a key holding the wrong kind of value
127.0.0.1:6379> hget user01
(error) ERR wrong number of arguments for 'hget' command
127.0.0.1:6379> hset use1 name "ygj"
(integer) 1
127.0.0.1:6379> hset use1 age 20
(integer) 1
127.0.0.1:6379> hget user1
(error) ERR wrong number of arguments for 'hget' command
127.0.0.1:6379> hget user1 name
(nil)
127.0.0.1:6379> hget use1 name
"ygj"
127.0.0.1:6379> hget use1 age
"20"
127.0.0.1:6379> hgetall use1
1) "name"
2) "ygj"
3) "age"
4) "20"
127.0.0.1:6379> hget user01 name
"john"
127.0.0.1:6379> desize
(error) ERR unknown command 'desize'
127.0.0.1:6379> dbsize
(integer) 5
127.0.0.1:6379> hlen user01
(integer) 2
127.0.0.1:6379> hlen usel1
(integer) 0
127.0.0.1:6379> hlen use1
(integer) 2
127.0.0.1:6379> lpush city a b c d
(integer) 4
127.0.0.1:6379> lrange city 0 -1
1) "d"
2) "c"
3) "b"
4) "a"
127.0.0.1:6379> lrange city 0 2
1) "d"
2) "c"
3) "b"
127.0.0.1:6379> rpush e f g
(integer) 2
127.0.0.1:6379> lrange city 0 -1
1) "d"
2) "c"
3) "b"
4) "a"
127.0.0.1:6379> rpush city e f g
(integer) 7
127.0.0.1:6379> lrange city 0 -1
1) "d"
2) "c"
3) "b"
4) "a"
5) "e"
6) "f"
7) "g"
127.0.0.1:6379> del e
(integer) 1
127.0.0.1:6379> lrang e 0 -1
(error) ERR unknown command 'lrang'
127.0.0.1:6379> rrange city 0 -1
(error) ERR unknown command 'rrange'
127.0.0.1:6379> lrange city 0 -1
1) "d"
2) "c"
3) "b"
4) "a"
5) "e"
6) "f"
7) "g"
127.0.0.1:6379> desize
(error) ERR unknown command 'desize'
127.0.0.1:6379> dbsize
(integer) 6
127.0.0.1:6379> sadd emals [email protected]
(integer) 1
127.0.0.1:6379> sadd emals [email protected]
(integer) 1
127.0.0.1:6379> smembers emals
1) "[email protected]"
2) "[email protected]"
127.0.0.1:6379> sismember emals [email protected]
(integer) 1
127.0.0.1:6379> sismember emals [email protected]
(integer) 0
127.0.0.1:6379> srem emals [email protected]
(integer) 1
127.0.0.1:6379> smembers emals
1) "[email protected]"

Golang 操作 Redis

Install a third-party open source libraries Redis

1) Use of a third party open source library redis: github.com/garyburd/redigo/redis
2) before use Redis, Redis to install third-party libraries, perform the installation instructions at GOPATH path:
D: \ goproject> Go GET GitHub. com / garyburd / redigo / redis

Special Note: Before installing Redis database, ensure that you have installed and configured Git, because it is downloaded from github install Redis libraries
need to use Git. If you do not configure through Git, please refer to: How to install Git Configuration

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写入数据 string [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)
}

Hash operation

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写入数据 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读取数据 

    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 
    }

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

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

A plurality of data operation

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写入数据 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("hget  err=", err)
        return 
    }
    for i, v := range r {
        fmt.Printf("r[%d]=%s\n", i, v)
    }

}

Similarly this operation may be set

Set the data valid time

Description: By Golang Redis of operation, key-value to the valid time
of the core code:

//给 name 数据设置有效时间为 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) a certain number of links prior initialization, the link into the pool
2) when required to operate Redis Go, taken directly from the link connection pooling Redis .
3) This saves the temporary link Redis get time to improve efficiency.

The sample code

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

//定义一个全局的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", "localhost: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 取出链接,一定保证链接池是没有关闭
    // 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)


}

Guess you like

Origin www.cnblogs.com/ygjzs/p/11913848.html