在云端安装好了redis,绑定了6379端口,设置开机自启动。
在电脑上用springboot+mybatis搭建了一个简单程序,用来连接远程的redis写数据。
一开始,往redis写数据时,发现控制台报 Unexpected end of stream 异常,百度后根据 https://github.com/xetorthio/jedis/issues/1029 中的解答重写了RedisConfig中获取连接池部分的代码,代码如下:
@Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(200); jedisPoolConfig.setMaxIdle(50); jedisPoolConfig.setMinIdle(8); jedisPoolConfig.setMaxWaitMillis(10000); jedisPoolConfig.setTestOnBorrow(true); jedisPoolConfig.setTestOnReturn(true); logger.info("******** Create jedis pool successfully! ********"); return jedisPoolConfig; }
重写后发现异常变成了:
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at
…
Caused by: java.util.NoSuchElementException: Unable to validate object at
…
搜索了一下,有人说是redis的网络ping不通或者防火墙导致访问不了,但我看了服务器,排除了这几个问题。
然后看到有人说把setTestOnBorrow(true)改成setTestOnBorrow(false)看看,然后看了下setTestOnBorrow里面的源码,这个方法会验证Jedis实例,如果不存在,会把异常封装后再抛出来,所以先把true改成false再试一次,发现异常变成以下信息:
(error) 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 lookback 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 --portected-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.
这个就是根本原因,redis有一个保护模式(Protected-mode ),为了禁止公网访问redis cache,加强redis安全的。
它启用的条件,有两个:
1) 没有bind IP
2) 没有设置访问密码
所以原因就是我redis数据库没有设置密码导致的无法从外网访问redis数据库,设置密码以后就可以正常访问了,解决。
参考资料:
https://blog.csdn.net/aubdiy/article/details/53511410
https://github.com/xetorthio/jedis/issues/1029
https://blog.csdn.net/a4810875/article/details/80669536
http://www.cnblogs.com/wangqingyi/articles/5575419.html
https://www.oschina.net/question/148950_166301
原文:https://www.cnblogs.com/shubiao/p/10669565.html