go redis

作者: 莫夏_b560 | 来源:发表于2019-01-03 17:55 被阅读0次

    go 操作redis操作

    package main
    
    import (
        "log"
        "fmt"
        "reflect"
        "github.com/gomodule/redigo/redis"
    )
    
    //http://www.cnblogs.com/wdliu/p/9330278.html
    
    //redis 数据类型
    
    type RedisConn struct {
        conn redis.Conn
    }
    
    //连接
    func redisConn(netWork, address string) (redis.Conn, error) {
        conn, err := redis.Dial(netWork, address)
        if err != nil {
            log.Println(err.Error())
            return nil, err
        }
        return conn, nil
    }
    
    //set string
    func (conn *RedisConn) SetString(key, value string) error {
        _, err := conn.conn.Do("SET", key, value)
        if err != nil {
            log.Println(err.Error())
            return err
        }
        return nil
    }
    
    //get string
    func (conn *RedisConn) GetString(key string) (string, error) {
        value, err := redis.String(conn.conn.Do("GET", key))
        if err != nil {
            log.Println(err.Error())
            return "", err
        }
        return value, nil
    }
    
    //set out time
    func (conn *RedisConn) SetExpire(key string, time int) error {
        _, err := conn.conn.Do("expire", key, time)
        if err != nil {
            log.Println(err.Error())
            return err
        }
        return nil
    }
    
    //批量获取mget、批量设置mset
    func (conn *RedisConn) mSet(keyValue ...string) error {
        _, err := conn.conn.Do("MSET", keyValue[0], keyValue[1], keyValue[2], keyValue[3])
        if err != nil {
            log.Println(err.Error())
            return err
        }
        return nil
    }
    
    func (conn *RedisConn) mGet(key ...string) {
        res, err := conn.conn.Do("MGET", key[0], key[1])
        if err != nil {
            log.Println(err.Error())
        }
    
        fmt.Printf("type: %s", reflect.TypeOf(res))
        fmt.Printf("value: %s", res)
    }
    
    //列表
    func (conn *RedisConn) lPush() {
        _, err := conn.conn.Do("LPUSH", "list1", "Java", "Python", "Golang")
        if err != nil {
            log.Println(err.Error())
        }
    }
    
    func (conn *RedisConn) lPop() {
        res, err := conn.conn.Do("LPOP", "list1")
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Printf("%s", res)
    }
    
    //hash
    func (conn *RedisConn) hashSet() {
        _, err := conn.conn.Do("HSET", "student", "name", "小雪")
        if err != nil {
            log.Println(err.Error())
        }
    }
    
    func (conn *RedisConn) hashGet() {
        res, err := conn.conn.Do("HGET", "student", "name")
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Printf("%s", res)
    }
    
    //hash more option
    func (conn *RedisConn) hashMSet() {
        _, err := conn.conn.Do("HMSET", "students", "name", "小雪", "age", 6, "sex", "女")
        if err != nil {
            log.Println(err.Error())
        }
    }
    
    func (conn *RedisConn) hashMGet() {
            //int64s 转换返回的数组值
        res, err := redis.Int64s(conn.conn.Do("HMGET", "students", "age"))
        if err != nil {
            log.Println(err.Error())
        }
    
        for k, v := range res {
            fmt.Println(k, v)
        }
    
        fmt.Printf("redis.int64 获取年龄:%d", res)
    }
    
    func (conn *RedisConn) poolGetConn() {
    
    }
    
    #连接池
    var Pool redis.Pool
    
    //MaxActive 最大连接数,即最多的tcp连接数,一般建议往大的配置,但不要超过操作系统文件句柄个数(centos下可以ulimit -n查看)。
    //MaxIdle 最大空闲连接数,即会有这么多个连接提前等待着,但过了超时时间也会关闭。
    //IdleTimeout 空闲连接超时时间,但应该设置比redis服务器超时时间短。否则服务端超时了,客户端保持着连接也没用。
    //Wait 这是个很有用的配置。好多东抄抄本抄抄的文章都没有提。如果超过最大连接,是报错,还是等待。
    
    func init() {
        Pool = redis.Pool{
            //最大的激活连接数,同时最多有N个连接
            MaxActive: 20,
            //最大的空闲连接数,即使没有redis连接时依然可以保持N个空闲的连接,而不被清除,随时处于待命状态
            MaxIdle: 10,
            //空闲连接等待时间,超过此时间后,空闲连接将被关闭
            IdleTimeout: 120,
            //
            Wait: true,
            //连接方法
            Dial: func() (redis.Conn, error) {
                return redisConn("tcp", "127.0.0.1:6379")
            },
        }
    }
    func main() {
        conn, err := redisConn("tcp", "127.0.0.1:6379")
        if err != nil {
            log.Println(err.Error())
        }
    
        defer conn.Close()
    
        redisConn := &RedisConn{conn: conn}
        err = redisConn.SetString("name", "JayeWu")
        if err != nil {
            log.Println(err.Error())
        }
    
        err = redisConn.SetExpire("name", 10)
        if err != nil {
            log.Println(err.Error())
        }
    
        name, err := redisConn.GetString("name")
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Println(name)
    
        redisConn.mSet("name", "Jaye", "sex", "男")
        redisConn.mGet("name", "sex")
    
        fmt.Println("########list########")
        redisConn.lPush()
        redisConn.lPop()
    
        fmt.Println("$$$$$$$$$$hash$$$$$$$$$$")
        redisConn.hashSet()
        redisConn.hashGet()
    
        fmt.Println("$$$$$$$$$$hash-M$$$$$$$$$$")
        redisConn.hashMSet()
        redisConn.hashMGet()
    
        fmt.Println("###########Pool############")
        pconn := Pool.Get()
        _, err = pconn.Do("SET", "home", "102004")
        if err != nil {
            log.Println(err.Error())
        }
        res, err := redis.String(pconn.Do("GET", "home"))
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Println("pool get value", res)
    }
    
    

    Pipelining(管道)

    package main
    
    import (
        "github.com/gomodule/redigo/redis"
        "fmt"
        "log"
    )
    
    func Pipelining(conn redis.Conn)  {
        conn.Send("HMSET","user", "name", "JD", "age", "18")
        conn.Send("HSET", "user","score","100")
        conn.Send("HGET", "user","age")
        conn.Flush()
    
        res1, err := conn.Receive()
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Printf("Receive res1:%v \n", res1)
        res2, err := conn.Receive()
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Printf("Receive res2:%v\n",res2)
        res3, err := conn.Receive()
        if err != nil {
            log.Println(err.Error())
        }
        fmt.Printf("Receive res3:%s\n",res3)
        //Receive res1:OK
        //Receive res2:1
        //Receive res3:18
    }
    
    func main() {
        conn, err := redis.Dial("tcp", "127.0.0.1:6379")
        if err != nil {
            log.Println(err.Error())
        }
        defer conn.Close()
    
        Pipelining(conn)
    }
    

    发布/订阅

    package main
    
    import (
        "github.com/gomodule/redigo/redis"
        "log"
        "fmt"
        "time"
    )
    
    func push(msg string) {
        conn, err := redis.Dial("tcp", "127.0.0.1:6379")
        if err != nil {
            log.Println(err.Error())
        }
        defer conn.Close()
    
        _, err = conn.Do("PUBLISH", "007", msg)
        if err != nil {
            log.Println(err.Error())
        }
    }
    
    func sub() {
        conn, err := redis.Dial("tcp", "127.0.0.1:6379")
        if err != nil {
            log.Println(err.Error())
        }
        defer conn.Close()
        sub := redis.PubSubConn{Conn: conn}
        sub.Subscribe("007")
        for {
            switch v := sub.Receive().(type) {
            case redis.Message:
                fmt.Println("msg", v.Channel, string(v.Data), v.Pattern)
                break
            case redis.Subscription:
                fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
                break
            case error:
                fmt.Println(v)
            }
        }
    }
    
    func main() {
        go push("this is 006")
        go sub()
        time.Sleep(time.Second * 3)
    
        //007: subscribe 1
        //msg 007 this is 006
    }
    
    

    事务

    package main
    
    import (
        "fmt"
        "github.com/gomodule/redigo/redis"
    )
    
    //MULTI, EXEC,DISCARD和WATCH是构成Redis事务的基础,当然我们使用go语言对redis进行事务操作的时候本质也是使用这些命令。
    //
    //MULTI:开启事务
    //
    //EXEC:执行事务
    //
    //DISCARD:取消事务
    //
    //WATCH:监视事务中的键变化,一旦有改变则取消事务。
    
    func main()  {
        conn,err := redis.Dial("tcp","10.1.210.69:6379")
        if err != nil {
            fmt.Println("connect redis error :",err)
            return
        }
        defer conn.Close()
        conn.Send("MULTI")
        conn.Send("INCR", "foo")
        conn.Send("INCR", "bar")
        r, err := conn.Do("EXEC")
        fmt.Println(r)
    }
    

    相关文章

      网友评论

          本文标题:go redis

          本文链接:https://www.haomeiwen.com/subject/wjdqrqtx.html