Redigo的获取速度很慢(40ms)

Simple get request to Redis through Golang Redigo takes ~ 40ms. At the same time executing the same get request through redis-cli takes ~ 0.040 ms. So how can I improve the performance?

I tried commenting defer connection close() and changing MaxIdle and MaxActive settings of Redigo without any success.

1)我的Redigo代码

package redis

import (
    "os"
    "os/signal"
    "syscall"
    "time"
    "app/utils/debug"

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

var (
    Pool *redis.Pool
)

func init() {
    Pool = newPool(os.Getenv("REDIS_HOST"), os.Getenv("REDIS_PASSWORD"))
    cleanupHook()
}

func newPool(server string, password string) *redis.Pool {

    return &redis.Pool{

        MaxIdle:     100,
        MaxActive:   200,
        IdleTimeout: 240 * time.Second,

        Dial: func() (redis.Conn, error) {
            c, err := redis.Dial("tcp", server)
            if err != nil {
                return nil, err
            }
            if password != "" {
                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 {
            _, err := c.Do("PING")
            return err
        },
    }
}

func cleanupHook() {
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    signal.Notify(c, syscall.SIGTERM)
    signal.Notify(c, syscall.SIGKILL)
    go func() {
        <-c
        Pool.Close()
        os.Exit(0)
    }()
}


// Get - gets redis key
func Get(key string) ([]byte, error) {
    defer debug.TimeExecutionMeasure(time.Now())
    fmt.Println("GET1", key, time.Now())
    conn := Pool.Get()
    fmt.Println("GET2", key, time.Now())
    // defer conn.Close()

    fmt.Println("GET3", key, time.Now())
    var data []byte
    data, err := redis.Bytes(conn.Do("GET", key))
    if err != nil {
        return data, fmt.Errorf("error getting key %s: %v", key, err)
    }
    fmt.Println("GET4", key, time.Now())
    return data, err
}

So the ~20ms takes Pool.Get() and another ~20ms takes redis.Bytes.

2)redis-cli〜0.04ms:

MULTI -> TIME -> GET key -> TIME -> EXEC

I get that this comparison with redis-cli is not correct, because we don't account time to establishing connection in redis-cli. But at least the Get operation itself should be fast. Why it takes 20ms ?

任何提示如何改进呢?因为目前对Postgres实例的请求比对Redis的请求快...

评论