Springboot链接虚拟机Redis, Connection refused

前言

自己使用Springboot测试分布式锁的时候, 发现连接不上虚拟机的Redis, 提示Connection refused, 网上查了很多解决办法, 最后终于解决了, 记录一下解决的情况.

注: 虚拟机里, 我给Redis配置了静态ip: 192.168.1.123, 还设置Redis开机启动(更换了Redis启动的配置文件)



解决办法

可以访问虚拟机的IP和端口的情况

  • 使用命令: telnet ip port, 如下, 则表示可以正常访问(我本机ip为: 192.168.1.7)
VitodeMacBook:VMware Fusion vito$ telnet 192.168.1.123 22
Trying 192.168.1.123...
Connected to 192.168.1.123.

​ ip+端口可以访问的情况下, 则不需要重新设置虚拟机的服务器网络连接, 只需要开放6379端口即可

  • 开放虚拟机的端口
    • 最简单的办法关闭防火墙, 使用命令: systemctl stop firewalld, 并使用命令: systemctl status firewalld, 出现Active: inactive则表示防火墙已经关闭
[root@linux_tomcat redis]# systemctl stop firewalld
[root@linux_tomcat redis]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Mon 2020-06-22 05:40:44 CST; 2s ago
     Docs: man:firewalld(1)
  Process: 799 ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS (code=exited, status=0/SUCCESS)
 Main PID: 799 (code=exited, status=0/SUCCESS)
  • 修改redis的配置文件: redis.conf, 注释掉配置文件里的这一行: bind 127.0.0.1
  • 注意, 这里修改配置文件的时候, 一定要修改redis启动时使用的配置文件, 我在测试的时候, 修改了原始配置文件, 结果一直访问不了, 费了老半天才发现, 我的redis服务器启动时, 用的不是原始的配置文件. 最后改了实际使用的配置文件后, redis连接正常了.
  • 再执行命令: telnet ip port, 测试连接redis
    • 出现如下情况, 说明需要再修改redis的配置文件: redis.conf, 将protected-mode yes 改成:protected-mode no 意思是不使用密码登录
VitodeMacBook:VMware Fusion vito$ telnet 192.168.1.123 6379
Trying 192.168.1.123...
Connected to 192.168.1.123.
Escape character is '^]'.
-DENIED Redis is running in protected mode because protected mode is enabled
  • 最后再执行命令: telnet ip port, 测试结果如下: redis连接成功
VitodeMacBook-Pro:VMware Fusion vito$ telnet 192.168.1.123 6379
Trying 192.168.1.123...
Connected to 192.168.1.123.

不可以访问虚拟机的IP和端口的情况

  • 使用命令: telnet ip port, 如下, 则表示不可以正常访问
VitodeMacBook:VMware Fusion vito$ telnet 192.168.1.123 22
Trying 192.168.1.123...
telnet: connect to address 192.168.1.123: Connection refused
telnet: Unable to connect to remote host

原因可能是以下几种:

  1. 本机ip和虚拟机IP不在同一网段内, 无法连通, 使用ping IP确认是否能连通, 解决办法:

  2. Linux 虚拟机的排查




参考来源

Linux 虚拟机:Network error: Connection refused 排查

VMware Fusion 端口映射

解决连接虚拟机的Redis时出现的拒绝访问和超时的问题

Mac上VMware Fusion的NAT端口映射+静态IP

解决redis connection refused: connect遇到的坑

配置CentOS7的网络为固定IP

原文地址:https://www.cnblogs.com/vitoboy/p/13185658.html