I'm using websocket to build a chat room and hope to store these message in redis in the process.So I build a redisPool by redigo.
func newPool(server, password string, db int) *redis.Pool {
return &redis.Pool{
MaxIdle: 256,
MaxActive: 0,
IdleTimeout: time.Duration(120),
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server,
redis.DialPassword(password),
redis.DialDatabase(db),
redis.DialConnectTimeout(500*time.Millisecond),
redis.DialReadTimeout(500*time.Millisecond),
redis.DialWriteTimeout(500*time.Millisecond))
if err != nil {
fmt.Printf("error: %s", err)
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < 5*time.Second {
return nil
}
_, err := c.Do("PING")
return err
},
}
}
And then, I got a redis connection instance in the redis pool when I call websocket request. Like this:
// ServeWs handles websocket requests from the peer.
func ServeWs(hub *Hub, c *gin.Context) {
res, err := Help.GetUserByToken(c)
if err != nil{
Help.JsonError(c, err)
return
}
userInfo, _ := res.(Models.User)
userName := userInfo.Username
roomID := c.Query("room_id")
// Get Redis Connection
pool := redis.RedisPool
redisConn := pool.Get()
defer redisConn.Close()
// Change Http to WebSocket
var upgrader = websocket.Upgrader{
// Solve Cors
CheckOrigin: func(r *http.Request) bool {
return true
},
}
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
fmt.Println(userName)
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256), username: []byte(userName), roomID: []byte(roomID)}
client.hub.register <- client
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump(&redisConn)
}
I want to write data into redis when I read message from client, so I added the Conn parameter to the readPump method, the conn is a pointer to redis connection, and the readPump function is like as:
func (c *Client) readPump(conn *redis.RedisConn) {
....
for {
...
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
message = []byte(string(c.roomID) + "&" + string(c.username) + ": " + string(message))
key := c.roomID
_, err = (*conn).Do("LPUSH", key, message)
if err != nil{
fmt.Printf("error: %s", err)
}
fmt.Println(string(message))
c.hub.broadcast <- []byte(message)
...
}
}
As you can see, I get the data through the client and try to store it in redis. But there is a error occuring:
error: dial tcp server: i/o timeout
I want to know how to solve the problem?
Thank you!
question from:
https://stackoverflow.com/questions/65882525/why-timeout-when-i-try-to-connect-redis-by-using-redigo