报错如下所示
redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to ***.***.***.***:6379 at redis.clients.jedis.Connection.connect(Connection.java:165) at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:109) at redis.clients.jedis.Connection.sendCommand(Connection.java:114) at redis.clients.jedis.BinaryClient.set(BinaryClient.java:133) at redis.clients.jedis.Client.set(Client.java:58) at redis.clients.jedis.Jedis.set(Jedis.java:153) at redis.clients.jedis.ShardedJedis.set(ShardedJedis.java:41) at com.lh.JedisPoolDemo.main(JedisPoolDemo.java:40) Caused by: java.net.SocketTimeoutException: connect timed out
1.查看云虚拟机是否对外开放了Redis的端口
步骤如下:
1.1 首先进入云管理控制台的本实例安全组
1.2 添加能对外访问的Redis端口
2. 修改Redis 配置文件redis.conf
2.1 修改bind
# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all the network interfaces available on the server.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
bind 127.0.0.1
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only into
# the IPv4 loopback interface address (this means Redis will be able to
# accept connections only from clients running into the same computer it
# is running).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT THE FOLLOWING LINE.
上面大概的意思就是你可以使用bind 绑定一个或者多个ip地址。如果你不绑定ip,默认所有的ip都可以监听到,但这样操作很危险,因此你需要设置一个登录密码。
如果你只绑定127.0.0.1表示只能监听本地ip访问Redis.既只能通过redis-cli访问redis.
所以要想外部访问有如下两种方式:
2.1.1. 第一种:注释bind,无绑定,添加密码
找到requirepass ,写入密码 ******
关闭 Redis 服务, 重新使用配置文件启动 Redis服务.
绑定了密码的话进入redis 需要输入验证指令 auth ******* :
2.1.2. 二:输入 ifconfig 命令,找到对外提供的ip和本地ip
绑定两个ip到 redis.conf 配置文件
关闭 Redis 服务, 重新使用配置文件启动 Redis服务.
3.jedis demo 访问 Redis demo 。
//host 为云虚拟机对外的ip ,也就是xshell 登录的ip.
Jedis jedis = new Jedis("47.98.151.13",6379);
jedis.auth("123456");
System.out.println(jedis.ping());
输出 pong 完美。。。
如果还不报错的话查看是否关闭了防火墙。关防火墙可以查看如下链接文章