golang操作redis

项目依赖地址go-redis

https://github.com/go-redis/redis

文档地址

https://pkg.go.dev/github.com/go-redis/redis/[email protected]#example-Client.Pipeline

  • 对于看go项目的文档我也是晕晕的,但是找到大概应该可以通过example下面来解决问题

docker安装redis

docker run --name redis507 -p 6379:6379 -d redis:5.0.7

docker run -it --network host --rm redis:5.0.7 redis-cli 【此步骤可以通过界面工具如:quickredis...等来查看连接】

redis连接

func initClient() (err error) {
    rdb = redis.NewClient(&redis.Options{
        Addr:     "localhost:6379",
        Password: "",  // no password set
        DB:       0,   // use default DB
        PoolSize: 100, // 连接池大小
    })

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

    _, err = rdb.Ping(ctx).Result()
    return err
}

操作string

func rdsString() {
    ctx := context.Background()
    if err := initClient(); err != nil {
        return
    }

    err := rdb.Set(ctx, "key1", "value1", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := rdb.Get(ctx, "jzredis").Result()
    if err != nil {
        panic(err)
    }
    fmt.Println("key1", val)
}

切换数据库

func changeDb(){
//切换数据库
    pipe := rdb.Pipeline()
    _ = pipe.Select(ctx, 3)
    _, _ = pipe.Exec(ctx)
    err = rdb.Set(ctx, "key3", "我是key3数据库请查看", 0).Err()
    if err != nil {
        panic(err)
    }
}

操作hash

func hsetTest()  {
    ctx := context.Background()
    if err := initClient(); err != nil {
        return
    }
    err := rdb.HSet(ctx, "testhset", map[string]interface{}{"org": 12345, "name": "test123"}).Err()
    if err != nil {
        panic(err)
    }

    fmt.Print("success")
}

操作列表


func listpushTest()  {
    ctx := context.Background()
    if err := initClient(); err != nil {
        return
    }
    for i := 0; i < 10; i++ {
        err := rdb.LPush(ctx, "listtest", i).Err()
        if err != nil {
            panic(err)
        }
    }

    fmt.Print("success")
}

func lPop()  {
    ctx := context.Background()
    if err := initClient(); err != nil {
        return
    }
    retstring, err := rdb.LPop(ctx, "listtest").Result()
    fmt.Print(retstring)
    if err != nil {
        panic(err)
    }
    fmt.Print("success")
}

func rPop()  {
    ctx := context.Background()
    if err := initClient(); err != nil {
        return
    }
    llen,_ := rdb.LLen(ctx,"listtest").Result()
    for i := int64(0); i < llen; i++ {
        retstring, err := rdb.RPop(ctx, "listtest").Result()
        fmt.Println(retstring)
        if err != nil {
            panic(err)
        }
    }
}

到此常用的redis已经记录了,如果还需要可以根据文档来时间的....

你可能感兴趣的:(golang操作redis)