第09讲:Spring Data Redis(RedisTemplate)

一、什么是SpringDataRedis

Spring-data-redis是spring大家族的一部分,提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

spring-data-redis针对jedis提供了如下功能:

  • 连接池自动管理,提供了一个高度封装的“RedisTemplate”类
  • 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
  • ValueOperations:简单K-V操作
  • SetOperations:set类型数据操作
  • ZSetOperations:zset类型数据操作
  • HashOperations:针对map类型的数据操作
  • ListOperations:针对list类型的数据操作

二、API

在pom.xml中引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml

spring:
  redis:
    port: 6379 # Redis服务器连接端口
    host: 127.0.0.1 # Redis服务器地址
    database: 0 # Redis数据库索引(默认为0)
    password: # Redis服务器连接密码(默认为空)
    timeout: 5000ms # 连接超时时间(毫秒)
    jedis:
      pool:
        max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
        max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-idle: 8 # 连接池中的最大空闲连接
        min-idle: 0 # 连接池中的最小空闲连接
server:
  port: 8070

2.1、RedisTemplate的直接方法

//删除单个key
public void delete(String key){
    
    
    redisTemplate.delete(key);
}

//删除多个key
public void deleteKey (String ...keys){
    
    
    redisTemplate.delete(keys);
}

//指定key的失效时间
public void expire(String key,long time){
    
    
    redisTemplate.expire(key,time,TimeUnit.MINUTES);
}

//根据key获取过期时间
public long getExpire(String key){
    
    
    Long expire = redisTemplate.getExpire(key);
    return expire;
}

//判断key是否存在
public boolean hasKey(String key){
    
    
    return redisTemplate.hasKey(key);
}

2.2、操作String

2.2.1、添加缓存

	@Test
    public void t1(){
    
    
        //方式1:通过redisTemplate设置值
        redisTemplate.boundValueOps("StringKey").set("StringValue");
        //同时设置过期时间
        redisTemplate.boundValueOps("StringKey").set("StringValue",1, TimeUnit.MINUTES);

        //方式2:通过BoundValueOperations设置值
        BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
        stringKey.set("StringVaule");
        //同时设置过期时间
        stringKey.set("StringValue",1, TimeUnit.MINUTES);

        //方式3:通过ValueOperations设置值
        ValueOperations ops = redisTemplate.opsForValue();
        ops.set("StringKey", "StringVaule");
        //同时设置过期时间
        ops.set("StringValue","StringVaule",1, TimeUnit.MINUTES);

        log.info("保存成功");
    }

2.2.2、获取缓存值

	@Test
    public void t2(){
    
    
        //方式1:通过redisTemplate设置值
        String str1 = (String) redisTemplate.boundValueOps("StringKey").get();

        log.info(str1);

        //方式2:通过BoundValueOperations获取值
        BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
        String str2 = (String) stringKey.get();

        //方式3:通过ValueOperations获取值
        ValueOperations ops = redisTemplate.opsForValue();
        String str3 = (String) ops.get("StringKey");
    }

2.2.3、设置过期时间

	@Test
    public void t3(){
    
    
        //方式1
        redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
        //方式2
        redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);
    }

2.3、操作Hash(key -> value)

2.3.1、添加缓存

	@Test
    public void t1(){
    
    
        //方式1:通过redisTemplate设置值
        redisTemplate.boundHashOps("HashKey").put("SmallKey", "HashVaue");

        //方式2:通过BoundValueOperations设置值
        BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
        hashKey.put("SmallKey", "HashVaue");

        //方式3:通过ValueOperations设置值
        HashOperations hashOps = redisTemplate.opsForHash();
        hashOps.put("HashKey", "SmallKey", "HashVaue");
    }

添加一整个Map集合

	@Test
    public void t9(){
    
    
        Map<String, String> en = new HashMap<>();
        en.put("hello1", "world1");
        en.put("hello2", "world2");
        en.put("hello3", "world3");
        redisTemplate.boundHashOps("HashKey").putAll(en);
    }

2.3.2、设置过期时间

	@Test
    public void t3(){
    
    
        redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
        redisTemplate.expire("HashKey",1, TimeUnit.MINUTES);
    }

2.3.2、根据key获取value

	@Test
    public void t2(){
    
    
        //方式1:通过redisTemplate获取
        String value1 = (String) redisTemplate.boundHashOps("HashKey").get("SmallKey");

        //方式2:通过BoundValueOperations获取值
        BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
        String value2 = (String) hashKey.get("SmallKey");

        //方式3:通过ValueOperations获取值
        HashOperations hashOps = redisTemplate.opsForHash();
        String value3 = (String) hashOps.get("HashKey", "SmallKey");

        log.info(value1);
    }

2.3.3、获取全部key

	@Test
    public void t4(){
    
    
        //方式1、通过redisTemplate获取值
        Set keys1 = redisTemplate.boundHashOps("HashKey").keys();

        //方式2、通过BoundValueOperations获取值
        BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
        Set keys2 = hashKey.keys();

        //方式3、通过ValueOperations获取值
        HashOperations hashOps = redisTemplate.opsForHash();
        Set keys3 = hashOps.keys("HashKey");

        Iterator itr = keys1.iterator();
        while (itr.hasNext()) {
    
    
            log.info(itr.next()+"");
        }
    }

2.3.4、获取全部value

	@Test
    public void t5(){
    
    
        //方式1、通过redisTemplate获取值
        List values1 = redisTemplate.boundHashOps("HashKey").values();

        //方式2、通过BoundValueOperations获取值
        BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
        List values2 = hashKey.values();

        //方式3、通过ValueOperations获取值
        HashOperations hashOps = redisTemplate.opsForHash();
        List values3 = hashOps.values("HashKey");

        for(Object v : values1){
    
    
            log.info(v+"");
        }
    }

2.3.5、获取全部key-value

	@Test
    public void t6(){
    
    
        //方式1、通过redisTemplate获取
        Map<Object, Object> entries = redisTemplate.boundHashOps("HashKey").entries();

        //方式2、通过BoundValueOperations获取值
        BoundHashOperations hashKey = redisTemplate.boundHashOps("HashKey");
        Map entries1 = hashKey.entries();

        //方式3、通过ValueOperations获取值
        HashOperations hashOps = redisTemplate.opsForHash();
        Map entries2 = hashOps.entries("HashKey");

       for (Map.Entry<Object, Object> en : entries.entrySet()) {
    
    
           Object key = en.getKey();
           Object value = en.getValue();
           log.info("key="+key+",value="+value);
       }
    }

2.3.6、删除

	@Test
    public void t7(){
    
    
        //删除小key
        redisTemplate.boundHashOps("HashKey").delete("SmallKey");
        //删除大key
        redisTemplate.delete("HashKey");
    }

2.3.7、判断是否包含某个key

	@Test
    public void t8(){
    
    
        boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");
        log.info(isEmpty ? "包含" : "不包含");
    }

2.4、操作List集合

2.4.1、添加缓存

	@Test
    public void t1(){
    
    
        //方式1、通过redisTemplate设置值
        redisTemplate.boundListOps("listKey").leftPush("listLeftValue1");
        redisTemplate.boundListOps("listKey").rightPush("listRightValue2");

        //方式2、通过BoundValueOperations设置值
        BoundListOperations listKey = redisTemplate.boundListOps("listKey");
        listKey.leftPush("listLeftValue3");
        listKey.rightPush("listRightValue4");

        //方式3、通过ValueOperations设置值
        ListOperations opsList = redisTemplate.opsForList();
        opsList.leftPush("listKey", "listLeftValue5");
        opsList.rightPush("listKey", "listRightValue6");
    }

将一整个List集合添加到缓存

    @Test
    public void t2(){
    
    
        List<String> list = new ArrayList<String>();
        redisTemplate.boundListOps("listKey").rightPushAll(list);
        redisTemplate.boundListOps("listKey").leftPushAll(list);
    }

2.4.2、设置过期时间

	@Test
    public void t3(){
    
    
        redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
        redisTemplate.expire("listKey",1, TimeUnit.MINUTES);
    }

2.4.3、获取元素个数

	@Test
    public void t4(){
    
    
        Long size = redisTemplate.boundListOps("listKey").size();
        log.info("个数:"+size);
    }

2.4.4、获取List全部元素

	@Test
    public void t5(){
    
    
    	//-1为打印全部
        List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10);
        for (Object en : listKey1) {
    
    
            log.info(en+"");
        }
    }

2.4.5、根据索引查询元素

	@Test
    public void t6(){
    
    
        String en = (String) redisTemplate.boundListOps("listKey").index(1);
        log.info(en);
    }

2.4.6、从左或从右弹出一个元素

	@Test
    public void t7(){
    
    
        String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop();  //从左侧弹出一个元素
        String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); //从右侧弹出一个元素
    }

2.4.7、根据索引修改List中的某条数据(key,索引,值)

	@Test
    public void t8(){
    
    
        //key,索引,值
        redisTemplate.boundListOps("listKey").set(3L,"hahaha");
    }

2.5、操作Set

2.5.1、添加Set缓存(值可以是一个,也可是多个)

	@Test
    public void t1(){
    
    
        //方式1、通过redisTemplate设置值
        redisTemplate.boundSetOps("setKey").add("setValue1", "setValue2", "setValue3");

        //方式2、通过BoundValueOperations设置值
        BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
        setKey.add("setValue1", "setValue2", "setValue3");

        //方式3、通过ValueOperations设置值
        SetOperations setOps = redisTemplate.opsForSet();
        setOps.add("setKey", "SetValue1", "setValue2", "setValue3");
    }

2.5.2、设置过期时间

	@Test
    public void t2(){
    
    
        redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
        redisTemplate.expire("setKey",1, TimeUnit.MINUTES);
    }

2.5.3、获取Set容器中的全部元素

    @Test
    public void t3(){
    
    
        //方式1、通过redisTemplate获取值
        Set set1 = redisTemplate.boundSetOps("setKey").members();

        //方式2、通过BoundValueOperations获取值
        BoundSetOperations setKey = redisTemplate.boundSetOps("setKey");
        Set set2 = setKey.members();

        //方式3、通过ValueOperations获取值
        SetOperations setOps = redisTemplate.opsForSet();
        Set set3 = setOps.members("setKey");

        for (Object en : set1) {
    
    
            log.info(en+"");
        }
    }

2.5.4、获取Set缓存的长度

long size = redisTemplate.boundSetOps("setKey").size();

2.5.5、根据value从一个set中查询,是否存在

boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");

2.5.5、删除元素

@Test
    public void t4(){
    
    
        //删除指定元素,返回成功删除的个数
        Long count = redisTemplate.boundSetOps("setKey").remove("setValue2", "setValue3", "setValue1");

        //删除全部元素,执行成功返回true
        Boolean isOk = redisTemplate.delete("setKey");
    }

2.6、操作ZSet

2.6.1、向缓存中添加数据并同时设置分数

    @Test
    public void t1(){
    
    
        //方式1、通过redisTemplate设置值
        redisTemplate.boundZSetOps("zSetKey").add("zSetVaule", 100D);

        //方式2、通过BoundValueOperations设置值
        BoundZSetOperations zSetKey = redisTemplate.boundZSetOps("zSetKey");
        zSetKey.add("zSetVaule", 100D);

        //方式3、通过ValueOperations设置值
        ZSetOperations zSetOps = redisTemplate.opsForZSet();
        zSetOps.add("zSetKey", "zSetVaule", 100D);
    }

向集合中插入多个元素,并设置分数

    @Test
    public void t2(){
    
    
        DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("赵六", 2.1D);
        DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("二哈", 3.3D);
        Set<DefaultTypedTuple> ts = new HashSet<DefaultTypedTuple>();
        ts.add(p1);
        ts.add(p2);
        redisTemplate.boundZSetOps("zSetKey").add(ts);
    }

2.6.2、按照排名先后(从小到大)打印指定区间内的元素, -1为打印全部

    @Test
    public void t3(){
    
    
        Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(0, -1);
        for (String s : range) {
    
    
            //获取指定元素的分数
            double score = redisTemplate.boundZSetOps("zSetKey").score(s);
            log.info(s+":"+score);
        }
    }

2.6.3、返回集合内指定分数范围的成员个数(Double类型)

long count = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);

2.6.4、返回集合内元素在指定分数范围内的排名(从小到大)

Set byScore = redisTemplate.boundZSetOps("zSetKey").rangeByScore(0D, 2.2D);

2.6.5、返回集合内的成员个数

long size = redisTemplate.boundZSetOps("zSetKey").size();

2.6.6、带偏移量和个数,(key,起始分数,最大分数,偏移量,个数)

    @Test
    public void t5(){
    
    
    	//用法和MySQL的limit一致
        Set<String> range = redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 100D, 0, 3);
        for (String s : range) {
    
    
            //获取指定元素的分数
            double score = redisTemplate.boundZSetOps("zSetKey").score(s);
            log.info(s+":"+score);
        }
    }

2.6.7、返回集合内元素的排名,以及分数(从小到大)

    @Test
    public void t6(){
    
    
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
    
    
            log.info(tuple.getValue() + " : " + tuple.getScore());
        }
    }

2.6.8、返回指定成员的排名

    @Test
    public void t7(){
    
    
        //从小到大第n位
        Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("王五");
        //从大到小第n位
        Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("王五");
    }

2.6.9、删除

//删除指定元素
redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");

//删除指定索引范围的元素(Long类型)
redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);

//删除指定分数范围内的元素(Double类型)
redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);

2.6.10、为指定元素加分(Double类型),返回加分后的结果

    @Test
    public void t8(){
    
    
        //在原有分数上做加法
        Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("王五",1.1D);
        log.info(score+"");
    }

猜你喜欢

转载自blog.csdn.net/qzc70919700/article/details/129994251
今日推荐