Redigo:尝试连接池时无效的内存地址或 nil 指针取消引用

Posted

技术标签:

【中文标题】Redigo:尝试连接池时无效的内存地址或 nil 指针取消引用【英文标题】:Redigo: Invalid memory address or nil pointer dereference while attempting to connect to pool 【发布时间】:2015-10-27 21:13:24 【问题描述】:

Redis 连接中......!恐慌:运行时错误:无效的内存地址或 nil 指针取消引用 [信号 0xb 代码=0x1 地址=0x28 pc=0x40154b] goroutine 1 [运行]: runtime.panic(0x52c6e0, 0x6b6348) /usr/lib/go/src/pkg/runtime/panic.c:266 +0xb6 main.func·001(0xc21005102c, 0x0, 0x4bcd4c, 0x1) /home/vinay10949/redischeck/redischeck.go:21 +0x10b github.com/garyburd/redigo/redis.(*Pool).get(0xc210051000, 0x0, 0xc2100378f0, 0x42dbdf, 0x7fbe9c177070) /usr/lib/go/src/pkg/github.com/garyburd/redigo/redis/pool.go:250 +0x3a2 github.com/garyburd/redigo/redis.(*Pool).Get(0xc210051000, 0x1, 0x1) > /usr/lib/go/src/pkg/github.com/garyburd/redigo/redis/pool.go :150 +0x27 main.main() /home/

vinay10949/redischeck/redischeck.go:29 +0x13e

package main

import (
    "flag"
    "fmt"
    "github.com/garyburd/redigo/redis"
    //"reflect"
)

var (
    redisAddress   = flag.String("10.12.2.121", "10.12.2.121:6379", "Address to the Redis server")
    maxConnections = flag.Int("max-connections", 10, "Max connections to Redis")
)

func main() 

    //Redis Connection
    redisPool := redis.NewPool(func() (redis.Conn, error) 

        con, err := redis.Dial("tcp", *redisAddress)
        con.Do("SELECT", 1)
        if err != nil 
            return nil, err
        
        return con, err
    , *maxConnections)

    fmt.Println("Redis Connecting...!")
    con := redisPool.Get()
    status, errStatus := con.Do("SET", "Name", "BookMyShow")
    if errStatus != nil 
        fmt.Println(errStatus)
     else 
        fmt.Println("Redis Connected")
    
    statusInsertion, _ := redis.String(status, errStatus)
    fmt.Println("Status of Insertion :" + statusInsertion)
    value, _ := redis.String(con.Do("GET", "Name"))
    fmt.Println("Value Retrieved : " + value)

【问题讨论】:

【参考方案1】:

您在使用返回值之后检查错误:

con, err := redis.Dial("tcp", *redisAddress)
con.Do("SELECT", 1) // Here you are using con which most likely is nil
if err != nil 
    return nil, err

将代码重新排列为:

con, err := redis.Dial("tcp", *redisAddress)
if err != nil 
    return nil, err

con.Do("SELECT", 1) // con should be used after checking for errors

【讨论】:

【参考方案2】:
con, err := redis.Dial("tcp", *redisAddress)
if err != nil 
    return nil, err

con.Do("SELECT", 0) //Select 0 for Nutcracker

【讨论】:

以上是关于Redigo:尝试连接池时无效的内存地址或 nil 指针取消引用的主要内容,如果未能解决你的问题,请参考以下文章

无法生成 ngrokpanic:运行时错误:无效的内存地址或 nil 指针取消引用

sql golang查询时,无效的内存地址或nil指针取消引用。

k6:WARpanic:运行时错误:无效的内存地址或 nil 指针取消引用

使用 mgo 的无效内存地址或 nil 指针取消引用

附加到结构切片时无效的内存地址或 nil 指针取消引用

为啥 gorm db.First() 会因“无效的内存地址或 nil 指针取消引用”而恐慌? [复制]