Go Redis

1.安装

  go get github.com/garyburd/redigo/redis

2.连接

package main

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

func main() {
	c, err := redis.Dial("tcp", "127.0.0.1:6801")
	if err != nil {
		fmt.Println("conn redis failed,", err)
		return
	}

	fmt.Println("redis conn success")

	defer c.Close()
}

3.执行命令

c.Do("set", "test", "123") // 执行命令,参数依次参入
//执行读取命令,读取后值是scaii码,需要通过redis.Int或者String转换为int或者String
v, err := redis.Int(c.Do("get", "test"))
v1, err := redis.String(c.Do("get", "test"))

fmt.Println("test is %s", v)
fmt.Println("test is %s", v1)

4. 连接池

package main

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

func main() {
	pool := redis.Pool{ //连接池
		MaxIdle:     16,  // 最小连击数
		MaxActive:   0,   //最大连接数
		IdleTimeout: 300, //连接超时时间
		Dial: func() (redis.Conn, error) { //获取连接方法
			return redis.Dial("tcp", "127.0.0.1:6701")

		},
	}
	c := pool.Get() //获取连接
	c.Do("set", "test", "1234")
	c.Close() //连接放回连接池
}
posted @ 2021-05-26 17:33  Xjng  阅读(95)  评论(0编辑  收藏  举报