Golang 操作 Redis

Redis 是比较常用的 k/v 数据库,这里使用 go-redis/redis 客户端来操作 redis, 安装客户端:

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

基本操作:

package main

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

func NewRedisClient() *redis.Client {
    client := redis.NewClient(&redis.Options{
        Addr:               "localhost:6379",
        Dialer:             nil,
        OnConnect:          nil,
        Password:           "",
        DB:                 0,
    })
    return client
}

func main() {

    client := NewRedisClient()
    defer client.Close()
    err := client.Set("name", "twn39", 0).Err()
    if err != nil {
        panic(err)
    }

    val, err := client.Get("name").Result()
    if err != nil {
        panic(err)
    }

    fmt.Printf("key: %s\n", val)
}