1. 程式人生 > 實用技巧 >Jedis 連不接雲虛擬機器的Redis可能的各種情況

Jedis 連不接雲虛擬機器的Redis可能的各種情況

報錯如下所示

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.jedisdemo訪問 Redis demo 。

//host 為雲虛擬機器對外的ip ,也就是xshell 登入的ip.   
Jedis jedis = new Jedis("47.98.151.13",6379);
jedis.auth(
"123456");
System.out.println(jedis.ping());

輸出 pong完美。。。

如果還不報錯的話檢視是否關閉了防火牆。關防火牆可以檢視如下連結文章

https://www.jb51.net/article/182633.htm