Using Redis (Redigo and Go-redis/redis) in Go combat--golang

Source: Internet
Author: User
Tags imap
This is a creation in Article, where the information may have evolved or changed.

Go get Github.com/alphazero/go-redis
Go get Github.com/simonz05/godis
Go get Github.com/garyburd/redigo
Go get Github.com/gosexy/redis
Go get Cgl.tideland.biz/redis

At present these five kinds of

Use of open Source Library Redigo

GitHub Address:
Https://github.com/garyburd/redigo

Document Address:
Http://godoc.org/github.com/garyburd/redigo/redis

Get:

go get github.com/garyburd/redigo/redis

Connect to Redis

package mainimport (    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()}

Read/write
The value written here never expires

package mainimport (    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    _, err = c.Do("SET", "mykey", "superWang")    if err != nil {        fmt.Println("redis set failed:", err)    }    username, err := redis.String(c.Do("GET", "mykey"))    if err != nil {        fmt.Println("redis get failed:", err)    } else {        fmt.Printf("Get mykey: %v \n", username)    }}

How to set expiration, you can use the set of additional parameters:

package mainimport (    "fmt"    "time"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    _, err = c.Do("SET", "mykey", "superWang", "EX", "5")    if err != nil {        fmt.Println("redis set failed:", err)    }    username, err := redis.String(c.Do("GET", "mykey"))    if err != nil {        fmt.Println("redis get failed:", err)    } else {        fmt.Printf("Get mykey: %v \n", username)    }    time.Sleep(8 * time.Second)    username, err = redis.String(c.Do("GET", "mykey"))    if err != nil {        fmt.Println("redis get failed:", err)    } else {        fmt.Printf("Get mykey: %v \n", username)    }}

Output:
Get Mykey:superwang
Redis Get Failed:redigo:nil returned

Bulk Write Read

MGET key [Key ...]
MSET key value [key value ...]

Bulk Write Read object (Hashtable)
Hmset key field value [field value ...]
Hmget key field [field ...]

detection value is present
EXISTS Key

package mainimport (    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    _, err = c.Do("SET", "mykey", "superWang")    if err != nil {        fmt.Println("redis set failed:", err)    }    is_key_exit, err := redis.Bool(c.Do("EXISTS", "mykey1"))    if err != nil {        fmt.Println("error:", err)    } else {        fmt.Printf("exists or not: %v \n", is_key_exit)    }}

Output:
exists or Not:false

Delete
DEL key [Key ...]

package mainimport (    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    _, err = c.Do("SET", "mykey", "superWang")    if err != nil {        fmt.Println("redis set failed:", err)    }    username, err := redis.String(c.Do("GET", "mykey"))    if err != nil {        fmt.Println("redis get failed:", err)    } else {        fmt.Printf("Get mykey: %v \n", username)    }    _, err = c.Do("DEL", "mykey")    if err != nil {        fmt.Println("redis delelte failed:", err)    }    username, err = redis.String(c.Do("GET", "mykey"))    if err != nil {        fmt.Println("redis get failed:", err)    } else {        fmt.Printf("Get mykey: %v \n", username)    }}

Output:
Get Mykey:superwang
Redis Get Failed:redigo:nil returned

Read and write JSON to Redis

package mainimport (    "encoding/json"    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    key := "profile"    imap := map[string]string{"username": "666", "phonenumber": "888"}    value, _ := json.Marshal(imap)    n, err := c.Do("SETNX", key, value)    if err != nil {        fmt.Println(err)    }    if n == int64(1) {        fmt.Println("success")    }    var imapGet map[string]string    valueGet, err := redis.Bytes(c.Do("GET", key))    if err != nil {        fmt.Println(err)    }    errShal := json.Unmarshal(valueGet, &imapGet)    if errShal != nil {        fmt.Println(err)    }    fmt.Println(imapGet["username"])    fmt.Println(imapGet["phonenumber"])}

Set Expiration Time
EXPIRE Key seconds

// 设置过期时间为24小时  n, _ := rs.Do("EXPIRE", key, 24*3600)  if n == int64(1) {      fmt.Println("success")  }  

List Operations
Command:

redis 127.0.0.1:6379> LPUSH runoobkey redis(integer) 1redis 127.0.0.1:6379> LPUSH runoobkey mongodb(integer) 2redis 127.0.0.1:6379> LPUSH runoobkey mysql(integer) 3redis 127.0.0.1:6379> LRANGE runoobkey 0 101) "mysql"2) "mongodb"3) "redis"

Code implementation:

package mainimport (    "fmt"    "github.com/garyburd/redigo/redis")func main() {    c, err := redis.Dial("tcp", "127.0.0.1:6379")    if err != nil {        fmt.Println("Connect to redis error", err)        return    }    defer c.Close()    _, err = c.Do("lpush", "runoobkey", "redis")    if err != nil {        fmt.Println("redis set failed:", err)    }    _, err = c.Do("lpush", "runoobkey", "mongodb")    if err != nil {        fmt.Println("redis set failed:", err)    }    _, err = c.Do("lpush", "runoobkey", "mysql")    if err != nil {        fmt.Println("redis set failed:", err)    }    values, _ := redis.Values(c.Do("lrange", "runoobkey", "0", "100"))    for _, v := range values {        fmt.Println(string(v.([]byte)))    }}

Output:
Mysql
Mongodb
Redis

Pipeline

The request/Response service can implement continuous processing of new requests even if the client is not ready to read the old response. This allows the client to send multiple commands to the server without waiting for a response, and finally to read multiple responses at once. This is pipelining (pipelining), a technology that has been used extensively for many years. Distance, many POP3 protocol implementations already support this feature, significantly speeding up the process of downloading new messages from the server.
Redis supports pipelining very early, so you can use piping technology regardless of the version you use

Connection support uses the Send (), Flush (), Receive () method to support pipelined operations

Send(commandName string, args ...interface{}) errorFlush() errorReceive() (reply interface{}, err error)

Send writes the command to the output buffer of the connection. Flush empties and writes the output buffers of the connection to the server side. The recevie reads the response of the server sequentially in FIFO order. The following example shows a simple pipeline:

c.Send("SET", "foo", "bar")c.Send("GET", "foo")c.Flush()c.Receive() // reply from SETv, err = c.Receive() // reply from GET

The Do method combines the Send,flush and receive methods. The Do method writes the command first, then empties the output buffer, and finally receives all pending responses, including the result of the command issued by the Do party. If any of the responses contain an error, do returns an error. If there is no error, the Do method returns the last response.

Use of open Source Library Go-redis/redis

GitHub Address:
Https://github.com/go-redis/redis

Document Address:
Https://godoc.org/github.com/go-redis/redis

Get:

go get -u github.com/go-redis/redis

Application:

package mainimport (    "fmt"    "github.com/go-redis/redis")func main() {    client := redis.NewClient(&redis.Options{        Addr:     "127.0.0.1:6379",        Password: "", // no password set        DB:       0,  // use default DB    })    pong, err := client.Ping().Result()    fmt.Println(pong, err)    err = client.Set("key", "value", 0).Err()    if err != nil {        panic(err)    }    val, err := client.Get("key").Result()    if err != nil {        panic(err)    }    fmt.Println("key", val)    val2, err := client.Get("key2").Result()    if err == redis.Nil {        fmt.Println("key2 does not exists")    } else if err != nil {        panic(err)    } else {        fmt.Println("key2", val2)    }}

Output:  
pong 
key value 
Key2 does not exists

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.