MDGSF Software Engineer

[GO] 使用redis

2017-10-25
GO

package main

import (
    "fmt"
    "time"

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

func newPool(addr string) *redis.Pool {
    return &redis.Pool{
        MaxIdle:     3,
        IdleTimeout: 240 * time.Second,
        Dial:        func() (redis.Conn, error) { return redis.Dial("tcp", addr) },
    }
}

func main() {
    testBasic()
    testHash()
    testPubSub()
}

func testPubSub() {
    pool := newPool("127.0.0.1:6379")
    psc := redis.PubSubConn{Conn: pool.Get()}
    psc.Subscribe("mychannel")
    for {
        switch v := psc.Receive().(type) {
        case redis.Message:
            fmt.Println("redis.Message", v.Channel, v.Data)
        case redis.Subscription:
            fmt.Println("redis.Subscription")
        case redis.PMessage:
            fmt.Println("redis.PMessage")
        case error:
            fmt.Println("find an error")
        }
    }
}

func testHash() {
    pool := newPool("127.0.0.1:6379")
    conn := pool.Get()
    defer conn.Close()

    testHGET(conn)

    testHSET(conn)
    testHGET(conn)

    testHDEL(conn)
    testHGET(conn)
}

func testHSET(conn redis.Conn) {
    conn.Do("HSET", "user1024", "roomID", 123)
}

func testHGET(conn redis.Conn) {
    buf, err := redis.String(conn.Do("HGET", "user1024", "roomID"))
    if err != nil && err != redis.ErrNil {
        fmt.Println("Get user room err:", err)
        return
    }

    fmt.Println("buf:", buf)
}

func testHDEL(conn redis.Conn) {
    conn.Do("HDEL", "user1024", "roomID")
}

func testBasic() {
    pool := newPool("127.0.0.1:6379")
    conn := pool.Get()
    defer conn.Close()

    conn.Do("SET", "hello", "world")
    s, _ := redis.String(conn.Do("GET", "hello"))
    fmt.Printf("%#v\n", s)
}

weixingongzhonghao

下一篇 [GO] 使用rsa

Comments

Content