[go]redis基本使用

Posted 毛台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[go]redis基本使用相关的知识,希望对你有一定的参考价值。

redis 数据结构操作

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


// set
c, err := redis.Dial("tcp", "localhost:16379")
_, err = c.Do("Set", "abc", 100)
r, err := redis.Int(c.Do("Get", "abc"))

//mset
_, err = c.Do("MSet", "abc", 100, "efg", 300)
r, err := redis.Ints(c.Do("MGet", "abc", "efg"))



//list
_, err = c.Do("lpush", "book_list", "abc", "ceg", 300)
r, err := redis.String(c.Do("rpop", "book_list"))

//hash字典
_, err = c.Do("HSet", "books", "abc", 100)
r, err := redis.Int(c.Do("HGet", "books", "abc"))


//超时
_, err = c.Do("expire", "abc", 10)

redis连接池

package main

import (
    "fmt"

    "github.com/garyburd/redigo/redis"
    "time"
)

var pool *redis.Pool

//初始化一个pool
func newPool(server, password string) *redis.Pool {
    return &redis.Pool{
        MaxIdle:     64,
        MaxActive:   1000,
        IdleTimeout: 240 * time.Second,
        Dial: func() (redis.Conn, error) {
            c, err := redis.Dial("tcp", server)
            if err != nil {
                return nil, err
            }
            /*
               if _, err := c.Do("AUTH", password); err != nil {
               c.Close()
               return nil, err
               }*/
            return c, err
        },
        TestOnBorrow: func(c redis.Conn, t time.Time) error {
            if time.Since(t) < time.Minute {
                return nil
            }
            _, err := c.Do("PING")
            return err
        },
    }
}

func main() {
    pool = newPool("localhost:16379", "")
    for {
        time.Sleep(time.Second)
        conn := pool.Get()
        conn.Do("set", "abc", 100)

        r, err := redis.Int(conn.Do("get", "abc"))
        if err != nil {
            fmt.Printf("do failed, err:%v
", err)
            continue
        }

        fmt.Printf("get from redis, result:%v
", r)
    }

    /*
        c, err := redis.Dial("tcp", "localhost:16379")
        if err != nil {
            fmt.Println("conn redis failed,", err)
            return
        }
        defer c.Close()
        _, err = c.Do("Set", "abc", 100)
        if err != nil {
            fmt.Println(err)
            return
        }
        r, err := redis.Int(c.Do("Get", "abc"))
        if err != nil {
            fmt.Println("get abc failed,", err)
            return
        }
        fmt.Println("get from redis", r)
    */
}

以上是关于[go]redis基本使用的主要内容,如果未能解决你的问题,请参考以下文章

Golang Redis 基本操作

Golang Redis 基本操作

go-redis

go中redis使用小结

Go_Redis

[Go] 通过 17 个简短代码片段,切底弄懂 channel 基础