go-redis连接池相关参数MaxIdle、IdleTimeout、MaxActive

2022-08-11 08:18:23

go-redis中连接池以及相关参数使用笔记

参数说明:

MaxIdle: 最大空闲连接数;没有redis操作时依然可以保持这个连接数量,但要在IdleTimeout的时间范围内,不然就会关闭,结合IdleTimeout进行理解;
MaxActive:最大连接数,一般为0,代表不限制;同一时间最多有这么多的连接,包括连接池中的连接以及连接池外的连接,假设最大空闲MaxIdle设置3,MaxActive设置4,那么,当连接池的连接全部处于忙碌状态时,如果这时候程序过来取连接,发现连接池没有取到,这时候就还可以再额外创建一个连接,当该连接关闭时,如果连接池中空闲数量小于3,则该连接会被放到连接池中,如果空闲数等于3,则该连接会直接关闭;
IdleTimeout:5 * 60 * time.Second,表示空闲连接保活时间,超过该时间后,连接会自动关闭,其实在默认情况下,当程序空闲时,redis连接池中是没有连接的;详情参见github,内容摘录如下:

This has been answered in github here. Just posting the relevant parts below:

PoolSize limits max number of open connections. If app is idle then go-redis does not open any connections.

New connection is opened when there is a command to process and there are no idle connections in the pool. Idle connections are closed after they are idle for IdleTimeout.

IdleCheckFrequency specifies how often we check if connection is expired. This is needed in case app is idle and there is no activity. Normally idle connections are closed when go-redis asks pool for a (healthy) connection.

获取Redis连接池的流程如下:

一般go程序运行时选设置redis连接池的初始化。假如我们设置MaxIdle:3,MaxActive:4时。
连接时: 调用pool.Get()时,先从MaxIdle中取出可用连接,如果失败,则看当前设置的MaxActive是否有超出最大数,没有超出则创建一个新的连接。
断开时: 调用conn.Close() 后,看当前连接数,如果比MaxIdle设置的数量大,则关闭redis连接。反之将连接放回到连接池中。
大体如下流程图所示:
获取连接流程图:
在这里插入图片描述
关闭连接流程图:
在这里插入图片描述
如有错误之处欢迎指出,感谢~

  • 作者:苑先森
  • 原文链接:https://blog.csdn.net/yuantao18800/article/details/119089923
    更新时间:2022-08-11 08:18:23