Golang 操作 Redis

github.com/gomodule/redigo/redis

package main

import (
	"fmt"
	"github.com/gomodule/redigo/redis"
)

func main() {
	c, err := redis.Dial("tcp", ":6379")
	if err != nil {
		fmt.Println("connect err: ", err)
		return
	}
	defer c.Close()
	
	// 通过 Send 和 Receive 发命令并异步接收返回结果,需要调 Flush 提交
	c.Send("SET", "foo", "bar")
	c.Send("GET", "foo")
	c.Flush()
	c.Receive()
	r, err := c.Receive() // reply from GET
	if err != nil {
		fmt.Println("Do err: ", err)
		return
	}
	fmt.Println(string(r.([]uint8)))
	
	// Do 方法发请求同时阻塞返回结果,内置类型转换函数得到对应类型
	r2, err2 := redis.String(c.Do("get", "foo"))	
	if err2 != nil {
		fmt.Println("Do get err: ", err2)
		return
	}
	fmt.Println(r2)
	
	r3, err3 := c.Do("lpush", "mylist", 3, "hello")
	if err3 != nil {
		fmt.Println("Do lpush err: ", err3)
		return
	}
	fmt.Println(r3)
	
	r4, err4 := redis.Strings(c.Do("lrange", "mylist", 0, -1))
	if err4 != nil {
		fmt.Println("Do lrange err: ", err4)
		return
	}
	fmt.Println(r4)
	
}

你可能感兴趣的:(Go/Golang)