duanfuxing2417 2014-02-25 04:50
浏览 262
已采纳

Golang增量数据到Redis

I have been playing around with golang and redis. I just stood up a simple http server and wanted to increment requests on redis. I am blowing up the connections (I think). I found that with redigo you can use connection pooling, but not sure how to implment that in go when I am serving the requests (where do you instantiate / call the pool from).

error: can't assign requested address.

Any suggestions would be appreciated....I am sure I am incorrectly making the connections, but just not sure how to change.

EDIT: Modified per pauljz's suggestions -- Works great now

    var pool redis.Pool

    func qryJson(rw http.ResponseWriter, req *http.Request){

        incrementRedis()
    }

    func incrementRedis () {

    t := time.Now().Format("2006-01-02 15:04:05")
    conn := pool.Get()
    defer conn.Close()
    if _, err := conn.Do("HINCRBY", "messages", t, 1); err != nil {
        log.Fatal(err)

    }


    }

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    pool = redis.Pool{
            MaxIdle: 50,
            MaxActive: 500, // max number of connections
            Dial: func() (redis.Conn, error) {
                    c, err := redis.Dial("tcp", ":6379")
                    if err != nil {
                            panic(err.Error())
                    }
                    return c, err
            },
    } 
    http.HandleFunc("/testqry", qryJson)
    log.Fatal(http.ListenAndServe(":8082", nil))
}
  • 写回答

2条回答 默认 最新

  • douyuan9512 2014-02-25 06:20
    关注

    The redigo docs have a good starter example for connection pooling: http://godoc.org/github.com/garyburd/redigo/redis#Pool

    In your case you would have a var pool redis.Pool in your package (i.e. not inside of a function).

    In main(), before your ListenAndServe call, you would call pool = redis.Pool{ ... } from the redigo example to initialize the pool.

    In incrementRedis() you would then do something like:

    func incrementRedis () {
        conn := pool.Get()
        defer conn.Close()
        if _, err := conn.Do("HINCRBY", "messages", t, 1); err != nil {
            log.Fatal(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗