解决Redis连接报错"ERR max number of clients reached"

问题发生原因

  • redis使用过程当中一般会由客户端进行连接资源管理,例如分配连接、监控连接状态、回收连接池资源
  • 默认设置下,redis不会主动断开连接
  • redistimeout参数配置项,默认单位是秒,当timeout是0的时候,redis不会主动关闭连接
  • 由于redis默认的最大连接数是10000,但是一直不关闭连接的话随着时间推移,连接越积越多,最终导致没有连接可用

最终导致redis客户端连接的时候报错,显示"ERR max number of clients reached"

获取当前redis配置

$ redis-cli
127.0.0.1:6379> CONFIG get * 
# 获取timeout可以执行
127.0.0.1:6379> CONFIG get timeout
1) "timeout"
2) "0"

解决方案

配置timout参数值

compose.yaml配置如下

redis:
    image: redis
    command: redis-server --requirepass testpasswd --timeout 10
    container_name: demo-redis
    restart: always
    oom_kill_disable: true
    mem_limit: 2g
    ports:
      - 127.0.0.1:6379:6379
    healthcheck:
      test: 'redis-cli ping || exit 1'

启动命令

redis-server --requirepass testpasswd --timeout 10

  • --requirepass testpasswd: 配置redis启动命令,设置启用密码连接,密码设置为testpasswd
  • --timeout 10: 配置当连接无操作10s之后连接会断开

其他参数解释

oom_kill_disable: true

  • 禁止当内存占用太多时候关闭容器

mem_limit: 2g

  • 限制最大使用2G内存

healthcheck

  • 使用健康检查容器是否服务正常

ports

  • 端口开放配置127.0.0.1:6379:6379表示不对外部机器开放6379端口

验证

$ docker exec -it demo-redis /bin/sh
# redis-cli
127.0.0.1:6379> auth testpasswd
127.0.0.1:6379> config get timeout
1) "timeout"
2) "10"

# 此处等待10秒之后再次输入命令,发现Broken pipe,这个是正常的,因为当前连接10s内没有操作,所以redis服务器关闭了该连接
127.0.0.1:6379> CONFIG get timeout
Error: Broken pipe
not connected> 

查看clients连接

127.0.0.1:6379> INFO clients
# Clients
connected_clients:168
cluster_connections:0
maxclients:10000
client_recent_max_input_buffer:20567
client_recent_max_output_buffer:0
blocked_clients:1
tracking_clients:0
clients_in_timeout_table:1

阅读参考

redis文件配置详解
redis官方文档

你可能感兴趣的:(解决Redis连接报错"ERR max number of clients reached")