实现Jedis连接
引入依赖
1 | <dependency> |
Java代码
1 | package com.ledao.jedis; |
运行代码时出现错误
代表连接超时了,我们配置下防火墙,开一个6379端口权限,如果是云服务器要开放6379的防火墙
1 | # 开端口 |
修改
/usr/local/redis/redis.conf
配置文件,将bind 127.0.0.1
注释掉,在前面加#
号即可(因为这里绑定了本机)
重启Redis服务
重启Redis服务,再次运行Java代码
1 | # 停止Redis服务 |
再次出现错误(下面是错误信息)
Exception in thread “main” redis.clients.jedis.exceptions.JedisDataException: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command ‘CONFIG SET protected-mode no’ from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing the Redis configuration file, and setting the protected mode option to ‘no’, and then restarting the server. 3) If you started the server manually just for testing, restart it with the ‘--protected-mode no’ option. 4) Setup a bind address or an authentication password. NOTE: You only need to do one of the above things in order for the server to start accepting connections from the outside.
at redis.clients.jedis.Protocol.processError(Protocol.java:127)
at redis.clients.jedis.Protocol.process(Protocol.java:161)
at redis.clients.jedis.Protocol.read(Protocol.java:215)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340)
at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:239)
at redis.clients.jedis.Jedis.set(Jedis.java:121)
at com.ledao.jedis.JedisTest.main(JedisTest.java:14)
出现错误的原因是因为远程连接 redis,因为 redis 的自我保护,会拒绝被访问,解决办法有两种:(推荐使用第二种方法:设置Redis连接密码)
关闭Redis的自我保护(不推荐使用)
protected-mode yes 的yes修改为
no
即可设置Redis连接密码,关闭Redis服务后就会失效,需要重新设置(推荐使用)
进入客户端
[root@localhost redis]#
./bin/redis-cli
设置密码
127.0.0.1:6379>
config set requirepass 123456
OK验证是否设置成功(出现OK就说明设置成功了)
127.0.0.1:6379>
auth 123456
OK退出客户端
127.0.0.1:6379>
quit
设置Redis密码
Java代码中设置Redis密码jedis.auth("123456")
,然后再次运行
1 | package com.ledao.jedis; |