具体情境如下,首先在linux机器上开启redis,
配置如下~
port:6379
ip:192.168.135.145
做法~在win下的idea连接linux中已经开启的redis,
看java后端代码~
```java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class jredisDemo01 {
public static void main(String[] args) {
/* JedisPool jedisPool = new JedisPool("192.168.135.145",6379);
Jedis jedis1 = jedisPool.getResource();
jedis1.set("person","name");*/
try {
Jedis jedis = new Jedis("192.168.135.145",6379);
jedis.set("fruit","lisi");
String fruit = jedis.get("fruit");
System.out.println(fruit);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
运行后结果报错~不能处理DNSname,根据提示查找可能是DNS解析问题,于是将host文件修改,添加了 192.168.135.145 redis
问题依旧存在;
```java
redis.clients.jedis.exceptions.JedisConnectionException: Failed to connect to any host resolved for DNS name.
at redis.clients.jedis.DefaultJedisSocketFactory.connectToFirstSuccessfulHost(DefaultJedisSocketFactory.java:63)
at redis.clients.jedis.DefaultJedisSocketFactory.createSocket(DefaultJedisSocketFactory.java:87)
at redis.clients.jedis.Connection.connect(Connection.java:180)
at redis.clients.jedis.Connection.sendCommand(Connection.java:152)
at redis.clients.jedis.Connection.executeCommand(Connection.java:121)
at redis.clients.jedis.Jedis.set(Jedis.java:4725)
at com.gavin.jredisDemo01.main(jredisDemo01.java:16)
Suppressed: java.net.SocketTimeoutException: connect timed out
at java.base/java.net.PlainSocketImpl.waitForConnect(Native Method)
at java.base/java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:107)
at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:399)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:242)
at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:224)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:403)
at java.base/java.net.Socket.connect(Socket.java:591)
at redis.clients.jedis.DefaultJedisSocketFactory.connectToFirstSuccessfulHost(DefaultJedisSocketFactory.java:73)
... 6 more
```
异常~`Failed to connect to any host resolved for DNS name. connect timed out`
异常发生之前----->>
1,注掉redis配置文件中bind--->>使得外部可以连接到redis (也可以指定连接地址)
![在这里插入图片描述](https://img-blog.csdnimg.cn/d8381f9581084d64ab5c80c46d5efc96.png)
2,保护模式已经关闭--->>不用输入密码可以连接
3,以设置守护模式 -->>使得redis可以在后台运行
可能是端口号没开放?
最后查看端口号是否对外开放~
```c
[root@localhost bin]# sudo firewall-cmd --zone=public --add-port=6379/tcp --permanent
success
[root@localhost bin]# systemctl restart firewalld
```
>注意~之后要重启防火墙,使得开放端口生效
再次运行代码~正常了