操作Redis

go-redis
创建于:2021年03月01日
import (
    "fmt"
    "github.com/go-redis/redis"

    )

var client *redis.Client

func init() {
    client = redis.NewClient(&redis.Options{
        Addr:         "127.0.0.1:6379",
        Password:     "123456",
        DB:           0
    })
}

key := "go"
valur := 1

err = client.Do("LPUSH", key, value).Err()

KEY操作

// 判断key是否存在
exist, err := client.Exists(key).Result()
// exist 为 1/0


// 设置key过期时间
client.Expire(key, time.Hour)

// 删除key
client.Del(key)

// 获取过期时间
tm, err := client.TTL("key").Result()
fmt.Println(tm)

字符串


err := redisdb.Set("key", "value", 1*time.Second).Err()
fmt.Println(err)

val, err := redisdb.Get("key").Result()
fmt.Println(val, err)

//不存在才设置 过期时间1秒
value, err := redisdb.SetNX("counter", 0, 1*time.Second).Result()
fmt.Println("setnx", value, err)

result, err := redisdb.Incr("counter").Result()
fmt.Println("Incr", result, err)

哈希

datas := map[string]interface{}{
        "name": "LI LEI",
        "sex":  1,
        "age":  28,
        "tel":  123445578,
    }

//添加
if err := redisdb.HMSet("hash_test", datas).Err(); err != nil {
    log.Fatal(err)
}

//获取指定key
rets, err := redisdb.HMGet("hash_test", "name", "sex").Result()
fmt.Println("rets:", rets, err)

//获取所有key,retAll类型map[string]string
retAll, err := redisdb.HGetAll("hash_test").Result()
fmt.Println("retAll", retAll, err)

//是否存在
bExist, err := redisdb.HExists("hash_test", "tel").Result()
fmt.Println(bExist, err)

bRet, err := redisdb.HSetNX("hash_test", "id", 100).Result()
fmt.Println(bRet, err)

//删除
fmt.Println(redisdb.HDel("hash_test", "age").Result())