文章目录
Jedis
什么是Jedis?
Jedis其实是Java Redis的缩写,就是用Java来操作Redis,之前服务器中的所有redis单条命令对应着Jedis中所有的方法的名字,它们是完全一致的,所以以后再操作Redis数据库的时候,没必要进入服务器中的Redis中,可以在Java中远程连接Redis来操作redis数据库;
Jedis测试
a.在idea中创建一个maven项目
如下图:
b.导入对应的依赖
如下图:
c.ping编码测试
ping一下,看看能否远程连接Redis,发现不能够远程连接redis,如下图:
把阿里云中安全组和阿里云中的云服务器的防火墙的端口号6379打开之后,仍会出现上面的不能远程连接的错误,这是因为默认Redis只能被本地连接,不能够被远程连接,我们需要改写一下redis.conf配置文件中的内容;
配置redis.conf配置文件里面的bind 127.0.0.1,把这句代码注释掉,如果不注释掉的话,只能够本地连接Redis,不能够通过Jedis远程连接Redis,注释操作如下图:
修改了redis.conf配置文件之后,需要重启服务器中的redis,然后在测试Jedis远程连接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:132)
at redis.clients.jedis.Protocol.process(Protocol.java:166)
at redis.clients.jedis.Protocol.read(Protocol.java:220)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:278)
at redis.clients.jedis.Connection.getStatusCodeReply(Connection.java:196)
at redis.clients.jedis.BinaryJedis.ping(BinaryJedis.java:199)
at com.xuanyuan.TestPing.main(TestPing.java:10)
上面的这个错误的大致意思就是开启了protected mode保护模式,我们需要把这个模式关闭,仍是去redis.conf的配置文件中寻找相关的字眼,如下图:
修改redis.conf配置文件的内容之后需要重启服务器中的redis,重启之后,在去测试用jedis远程连接redis,发现可以ping的通了,如下图:
d.使用jedis远程操作Redis
以后之前Redis中所有的单条命令以后都可以在java中通过Jedis的方法来实现,如下图:
通过Jedis再次理解Redis中的事务
使用Jedis操作Redis中的事务如下图: