gpt4 book ai didi

go - redigo 不同的池连接到单个服务器

转载 作者:IT王子 更新时间:2023-10-29 02:21:29 26 4
gpt4 key购买 nike

所以,我有必要连接到 3 个 redis 服务器。我创建了 3 个连接池,并初始化了它们中的每一个。但是 redigo 似乎只连接到单个 redis 服务器,尽管我使用不同的池获得连接。

使用 redigo,下面是我的代码

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

var poolA *redis.Pool
var poolB *redis.Pool
var poolC *redis.Pool

func main() {
poolA = &redis.Pool{}
poolB = &redis.Pool{}
poolC = &redis.Pool{}

connections := []string{"localhost:6379", "localhost2:6379", "localhost3:6379"}

for k, v := range connections {
redisPool := &redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", v)
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
IdleTimeout: time.Duration(10) * time.Second,
MaxActive: 100,
MaxIdle: 100 / 2,
Wait: true,
}

if k == 0 {
fmt.Println("poolA:", v)
poolA = redisPool
}
if k == 1 {
fmt.Println("poolB:", v)
poolB = redisPool
}
if k == 2 {
fmt.Println("poolC:", v)
poolC = redisPool
}
}

con := poolA.Get()
defer con.Close()
count, err := redis.Int(con.Do("SADD", "any:test", 3246))
if err != nil {
fmt.Println("error querying redis:", err.Error())
}
fmt.Println("count=", count)

con2 := poolB.Get()
defer con2.Close()
count, err = redis.Int(con2.Do("SADD", "any:test", 3246))
if err != nil {
fmt.Println("error querying redis:", err.Error())
}
fmt.Println("count=", count)

con3 := poolC.Get()
defer con3.Close()
count, err = redis.Int(con3.Do("SADD", "any:test", 3246))
if err != nil {
fmt.Println("error querying redis:", err.Error())
}
fmt.Println("count=", count)
}

问题是,所有 3 个池都连接到最后一个服务器/连接,结果如下所示。任何想法?

poolA: localhost:6379
poolB: localhost2:6379
poolC: localhost3:6379
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0
error querying redis: dial tcp: lookup localhost3: no such host
count= 0

Process finished with exit code 0

最佳答案

拨号函数使用单个变量v。这些函数在调用时使用分配给 v 的最后一个值。

要解决此问题,请在 for 循环范围内声明一个变量并在拨号函数中使用该变量:

for k, v := range connections {
v := v // Declare variable scoped inside for loop
redisPool := &redis.Pool{
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", v) // uses variable scoped inside for loop
},
...

除了这个问题之外,池设置没有意义。因为池被配置为丢弃空闲 10 秒的连接,借用功能测试从不 ping 服务器。

关于go - redigo 不同的池连接到单个服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47330048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com