一、目录展示
二、导入依赖
<!-- https://mvnrepository.com/artifact/redis.clients/jedis --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
三、RedisTest类
(1)连接Redis
(2)redis操作String
/** * jedis操作String */ @Test public void operationString(){ //切换数据库 //jedis.select(1); //设置一个string类型的key-value jedis.set("key01","value01"); //如何设置key的有效期 以秒为单位 //jedis.expire("key01",20); //获取string数据 String value = jedis.get("key01"); System.out.println("对应存放的value值为:"+value); //修改数据 jedis.set("key01","value001"); //删除数据 //jedis.del("key01"); //设置多个值 jedis.mset("key01","value01","key02","value02","key03","value03","key04","11"); //+1操作 //jedis.incr("key04"); //-1操作 //jedis.decr("key04"); //拼接 jedis.append("key04","append"); }
拼接效果:
(3)redis操作list
/** * jedis操作list */ @Test public void operationList(){ //清空集合值 jedis.del("listkey01","listkey02"); //设置list集合值,左侧插入 jedis.lpush("listkey01","北京","上海","广州"); //设置list集合值,右侧插入 jedis.rpush("listkey02","张三","李四","王五"); //获取list集合值 List<String> listkey01 = jedis.lrange("listkey01", 0, 10); for(String item:listkey01){ System.out.println(item); } //更改list集合数据 jedis.lset("listkey02",0,"赵六"); }
(4)redis操作set
/** * jedis操作set */ @Test public void operationSet(){ //设置set集合 jedis.sadd("setkey01","张三","王五","赵六"); //获取set值 Set<String> setkey01 = jedis.smembers("setkey01"); for(String item:setkey01){ System.out.println(item); } }
(5)redis操作SortedSet
/** * jedis操作SortedSet */ @Test public void operationSortedSet(){ //设置SortedSet jedis.zadd("setkey02",1,"北京"); jedis.zadd("setkey02",2,"上海"); //获取SortedSet值 Set<String> setkey02 = jedis.zrange("setkey02",0,-1); for(String item:setkey02){ System.out.println(item); } }
(6)redis操作map
/** * jedis操作Map */ @Test public void operationMap(){ //设置Map Map<String,String> map=new HashMap<>(); map.put("name","张三"); map.put("age","15"); jedis.hmset("mapkey01",map); //获取值 List<String> value = jedis.hmget("mapkey01", "name", "age"); for (String item:value){ System.out.println(item); } Map<String, String> all = jedis.hgetAll("mapkey01"); }