go 使用 redis

 

Redis 官网中推荐使用的 go 客户端是 Radix: https://github.com/mediocregopher/radix.v2 和 Redigo https://github.com/gomodule/redigo

先学习一下 Redigo

文档: https://godoc.org/github.com/gomodule/redigo/redis

Windows 中的 Redis Server

Redis 居然也有 Windows 版的了:

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

D:\java\Redis>redis-server.exe redis.windows.conf
[15508] 30 Jul 16:39:14.414 # Creating Server TCP listening socket *:6379: bind: No error

D:\java\Redis>redis-cli
127.0.0.1:6379> dbsize
(integer) 0
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379>

Go 中使用

获取:

$ go get github.com/gomodule/redigo/redis

连接 Redis

package main

import (
    "fmt"
    "github.com/gomodule/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")
     // 设置过期
    // _, err = c.Do("SET", "mykey", "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.Println("Get mykey: %v \n", username)
    }
    
   
    
}

参考连接:

« EOF »

If you like TeXt, don’t forget to give me a star :star2:.