使用jedis连接redis

1、导入jar包,添加pom依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2、测试连接
public static void main(String[] args) {
Jedis jedis = new Jedis("192.168.33.128",6379);
jedis.auth("123456");
System.out.println(jedis.ping());
jedis.close();
}
3、连接异常
Exception in thread "main" redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect
timed out
at redis.clients.jedis.Connection.connect(Connection.java:207)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:93)
at redis.clients.jedis.Connection.sendCommand(Connection.java:126)
at redis.clients.jedis.Connection.sendCommand(Connection.java:117)
at redis.clients.jedis.Jedis.get(Jedis.java:152)
at util.Test.main(Test.java:12)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:75)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at redis.clients.jedis.Connection.connect(Connection.java:184)
... 5 more
4、连接异常处理
1)关闭防火墙.(可能linux防火墙作用,限制了端口的出入)
systemctl stop firewalld.service
2)修改redis.conf文件


将 bind 127.0.0.1这一行注释掉
bind的意思是指定redis只接收来自该IP的请求,如果不设置,那么将处理所有请求,在生产环节中最好设置该项
将protected-mode yes 改为no 或 将 protected-mode yes 改为yes 并添加 requirepass 123456 设置密码
Protected-mode 是为了禁止公网访问redis cache,加强redis安全的。
3)重启redis服务


5、测试连接
测试程序出现PONG表示连接成功

posted @ 2019-03-21 14:00  我用代码主宰世界  阅读(2440)  评论(0编辑  收藏  举报