关于golang:golang操作redis

53次阅读

共计 3783 个字符,预计需要花费 10 分钟才能阅读完成。

装置 redis

本文视频教程:https://www.bilibili.com/vide…

下载 redis

这里在 windows 平台下测试

https://github.com/MicrosoftArchive/redis/releases

启动 server

执行redis-server.exe

C:\Program Files\Redis>redis-server.exe
[12092] 10 Aug 13:29:08.616 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server.exe /path/to/redis.conf
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 3.0.504 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 ('      ,       .-`  | `,)     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 12092
  `-._    `-._  `-./  _.-'_.-'
 |`-._`-._    `-.__.-'_.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           http://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'|`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'`-._    `-.__.-'    _.-'`-._        _.-'
              `-.__.-'

[12092] 10 Aug 13:29:08.619 # Server started, Redis version 3.0.504
[12092] 10 Aug 13:29:08.619 * The server is now ready to accept connections on port 6379

客户端测试

执行redis-cli.exe

127.0.0.1:6379> set name duoke360
OK
127.0.0.1:6379> get name
"duoke360"
127.0.0.1:6379>

装置 go-redis 库

应用 go get 命令装置

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

初始化数据库连贯

package main

import (
    "context"
    "github.com/go-redis/redis"
    "time"
)

// 申明一个全局的 rdb 变量
var rdb *redis.Client


// 初始化连贯
func initClient() (err error) {
    rdb = redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })
    
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    _, err = rdb.Ping(ctx).Result()
    if err != nil {return err}
    return nil
}

func main() {initClient()

}

连贯 Redis 哨兵模式

func initClient()(err error){
    rdb := redis.NewFailoverClient(&redis.FailoverOptions{
        MasterName:    "master",
        SentinelAddrs: []string{"x.x.x.x:26379", "xx.xx.xx.xx:26379", "xxx.xxx.xxx.xxx:26379"},
    })
    _, err = rdb.Ping().Result()
    if err != nil {return err}
    return nil
}

连贯 Redis 集群模式

func initClient()(err error){
    rdb := redis.NewClusterClient(&redis.ClusterOptions{Addrs: []string{":7000", ":7001", ":7002", ":7003", ":7004", ":7005"},
    })
    _, err = rdb.Ping().Result()
    if err != nil {return err}
    return nil
}

字符串 get、set

package main

import (
    "context"
    "fmt"
    "github.com/go-redis/redis"
    "time"
)

// 申明一个全局的 rdb 变量
var rdb *redis.Client
var ctx context.Context
var cancel context.CancelFunc
// 初始化连贯
func initClient() (err error) {
    rdb = redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "", // no password set
        DB:       0,  // use default DB
    })

    ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)

    _, err = rdb.Ping(ctx).Result()
    if err != nil {return err}
    return nil
}

func testStringGetSet() {err := rdb.Set(ctx,"score", 100, 0).Err()
    if err != nil {fmt.Printf("set score failed, err:%v\n", err)
        return
    }

    val, err := rdb.Get(ctx,"score").Result()
    if err != nil {fmt.Printf("get score failed, err:%v\n", err)
        return
    }
    fmt.Println("score", val)

    val2, err := rdb.Get(ctx,"name").Result()
    if err == redis.Nil {fmt.Println("name does not exist")
    } else if err != nil {fmt.Printf("get name failed, err:%v\n", err)
        return
    } else {fmt.Println("name", val2)
    }
    defer cancel()}

测试

func main() {initClient()
    testStringGetSet()}

运行后果

score 100
name duoke360

zset 示例

func testSet()  {
    zsetKey := "book_price"
    languages := []redis.Z{redis.Z{Score: 90.0, Member: "Golang"},
        redis.Z{Score: 98.0, Member: "Java"},
        redis.Z{Score: 95.0, Member: "Python"},
        redis.Z{Score: 97.0, Member: "JavaScript"},
        redis.Z{Score: 99.0, Member: "C/C++"},
    }
    // ZADD
    num, err := rdb.ZAdd(ctx,zsetKey, languages).Result()
    if err != nil {fmt.Printf("zadd failed, err:%v\n", err)
        return
    }
    fmt.Printf("zadd %d succ.\n", num)

    // 把 Golang 的分数加 10
    newScore, err := rdb.ZIncrBy(ctx,zsetKey, 10.0, "Golang").Result()
    if err != nil {fmt.Printf("zincrby failed, err:%v\n", err)
        return
    }
    fmt.Printf("Golang's score is %f now.\n", newScore)

    // 取分数最高的 3 个
    ret, err := rdb.ZRevRangeWithScores(ctx,zsetKey, 0, 2).Result()
    if err != nil {fmt.Printf("zrevrange failed, err:%v\n", err)
        return
    }
    for _, z := range ret {fmt.Println(z.Member, z.Score)
    }

    // 取 95~100 分的
    op := redis.ZRangeBy{
        Min: "95",
        Max: "100",
    }
    ret, err = rdb.ZRangeByScoreWithScores(ctx,zsetKey, op).Result()
    if err != nil {fmt.Printf("zrangebyscore failed, err:%v\n", err)
        return
    }
    for _, z := range ret {fmt.Println(z.Member, z.Score)
    }
}

func main() {initClient()
    testStringGetSet()}

正文完
 0