目录
1 前言
之前我们使用的redis命令都是通过命令行的形式实现的,那么如何使用Java来操作redis呢?联想到之前可以通过jdbc来操作数据库,同理也可以通过jedis来操作redis。
2 相关操作
Jedis相关依赖:
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency>
redis.conf配置文件注意事项:
1)bind=127.0.0.1只能接受本机的访问请求,不写的情况下,无限制接受任何ip地址的访问
2)protected-mode 将本机访问模式设为no
如果依然是连接不上可以参考这篇文章:阿里云中Redis远程连接不上解决方案(连接RedisDesktopManager,连接springboot项目)_ccboy爱Java-CSDN博客_阿里云redis远程连接不上
3 Jedis-API
首先先测试是否能够连接上远程的redis
public static void main(String[] args) { //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); //查看redis能否ping通 String ping = jedis.ping(); System.out.println(ping); }
测试结果
操作key
@Test public void demo1(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); //添加值 jedis.set("name","lucy"); //获取key String name = jedis.get("name"); System.out.println(name); Set<String> keys = jedis.keys("*"); for (String key : keys) { System.out.println(key); } }
结果:
操作string:
@Test public void demo1(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); jedis.mset("k1","v1","k2","v2"); List<String> mget = jedis.mget("k1", "k2"); System.out.println(mget); Set<String> keys = jedis.keys("*"); for (String key : keys) { System.out.println(key); } }
结果:
操作List:
@Test public void demo2(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); jedis.lpush("key1","lucy","marry","jack"); List<String> key1 = jedis.lrange("key1", 0, -1); System.out.println(key1); }
结果:
操作set
@Test public void demo3(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); jedis.sadd("names","lucy","marry"); Set<String> names = jedis.smembers("names"); System.out.println(names); }
结果:
操作hash
@Test public void demo4(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); jedis.hset("users","age","20"); String hget = jedis.hget("users", "age"); System.out.println(hget); }
结果:
操作zset
@Test public void demo5(){ //创建jedis对象 Jedis jedis = new Jedis("47.118.53.22",6379); jedis.zadd("china",100d,"shanghai"); Set<String> china = jedis.zrange("china", 0, -1); System.out.println(china); }
结果: