• RedisTemplate操作Redis


    一、SpringDataRedis简介

    1、Redis

    redis是一款开源的key-value数据库,运行在内存中,由C语言编写。企业开发通常采用Redis来实现缓存。同类的产品还有memcachememcached

    Memcached类似,Redis支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set – 有序集合)和hash(哈希类型)。这些数据类型都支持push/popadd/remove及取交集并集差集及更丰富的操作,这些操作都是原子性的。

    2、Jedis

    JedisRedis官方推出的一款面向Java的客户端,提供了很多接口供Java语言调用。可以在Redis官网下载,当然还有一些开源爱好者提供的客户端,如JredisSRP等等,推荐使用Jedis

    3、Spring Data Redis

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

    1.连接池自动管理,提供了一个高度封装的“RedisTemplate”

    2.针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口


    • ValueOperations:简单K-V操作
    • SetOperationsset类型数据操作
    • ZSetOperationszset类型数据操作
    • HashOperations:针对map类型的数据操作
    • ListOperations:针对list类型的数据操作

    3. 提供了对key“bound”(绑定)便捷化操作API,可以通过bound封装指定的key,然后进行一系列的操作而无须“显式”的再次指定Key,即BoundKeyOperations


    • BoundValueOperations
    • BoundSetOperations
    • BoundListOperations
    • BoundSetOperations
    • BoundHashOperations

    4.将事务操作封装,有容器控制。

    5.针对数据的“序列化/反序列化”,提供了多种可选择策略(RedisSerializer)

    JdkSerializationRedisSerializer:POJO对象的存取场景,使用JDK本身序列化机制,将pojo类通过ObjectInputStream/ObjectOutputStream进行序列化操作,最终redis-server中将存储字节序列。是目前最常用的序列化策略。

    StringRedisSerializerKey或者value为字符串的场景,根据指定的charset对数据的字节序列编码成string,是**“new String(bytes, charset)”“string.getBytes(charset)”**的直接封装。是最轻量级和高效的策略。

    JacksonJsonRedisSerializerjackson-json工具提供了javabeanjson之间的转换能力,可以将pojo实例序列化成json格式存储在redis中,也可以将json格式的数据转换成pojo实例。因为jackson工具在序列化和反序列化时,需要明确指定Class类型,因此此策略封装起来稍微复杂(需要jackson-mapper-asl工具支持)。

    二、RedisTemplate中API使用

    1、pom.xml依赖

    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、配置文件

    # Redis服务器连接端口
    spring.redis.port = 6379
    # Redis服务器地址
    spring.redis.host = 127.0.0.1
    # Redis数据库索引(默认为0)
    spring.redis.database = 0
    # Redis服务器连接密码(默认为空,建议设置密码)
    spring.redis.password = 666666
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.jedis.pool.max-active = 8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.jedis.pool.max-wait = -1ms
    # 连接池中的最大空闲连接
    spring.redis.jedis.pool.max-idle = 8
    # 连接池中的最小空闲连接
    spring.redis.jedis.pool.min-idle = 0
    # 连接超时时间(毫秒)
    spring.redis.timeout = 5000ms
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3、RedisTemplate的直接方法

    首先使用@Autowired注入RedisTemplate(后面直接使用,就不特殊说明)

    @Autowired
    private RedisTemplate redisTemplate;
    
    • 1
    • 2

    1)、删除单个key

    //删除一个key
    public void delete(String key){
        redisTemplate.delete(key);
    }
    
    • 1
    • 2
    • 3
    • 4

    2)、删除多个key

    //删除多个key
    public void deleteKey (String ...keys){
        redisTemplate.delete(keys);
    }
    
    • 1
    • 2
    • 3
    • 4

    3)、指定key的失效时间

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

    4)、根据key获取过期时间

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

    5)、判断key是否存在

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

    4、String类型相关操作

    1)、添加缓存

    //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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2)、设置过期时间(单独设置)

    redisTemplate.boundValueOps("StringKey").expire(1,TimeUnit.MINUTES);
    redisTemplate.expire("StringKey",1,TimeUnit.MINUTES);
    
    • 1
    • 2

    3)、获取缓存值

    //1、通过redisTemplate设置值
    String str1 = (String) redisTemplate.boundValueOps("StringKey").get();
    
    //2、通过BoundValueOperations获取值
    BoundValueOperations stringKey = redisTemplate.boundValueOps("StringKey");
    String str2 = (String) stringKey.get();
    
    //3、通过ValueOperations获取值
    ValueOperations ops = redisTemplate.opsForValue();
    String str3 = (String) ops.get("StringKey");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4)、删除key

    Boolean result = redisTemplate.delete("StringKey");
    
    • 1

    5)、顺序递增

    redisTemplate.boundValueOps("StringKey").increment(3L);
    
    • 1

    6)、顺序递减

    redisTemplate.boundValueOps("StringKey").increment(-3L);
    
    • 1

    5、Hash类型相关操作

    1)、添加缓存

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2)、设置过期时间(单独设置)

    redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
    redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);
    
    • 1
    • 2

    3)、添加一个Map集合

    HashMap<String, String> hashMap = new HashMap<>();
    redisTemplate.boundHashOps("HashKey").putAll(hashMap );
    
    • 1
    • 2

    4)、设置过期时间(单独设置)

    redisTemplate.boundValueOps("HashKey").expire(1,TimeUnit.MINUTES);
    redisTemplate.expire("HashKey",1,TimeUnit.MINUTES);
    
    • 1
    • 2

    5)、提取所有的小key

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    6)、提取所有的value值

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    7)、根据key提取value值

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    8)、获取所有的键值对集合

    //1、通过redisTemplate获取
    Map 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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    9)、删除

    //删除小key
    redisTemplate.boundHashOps("HashKey").delete("SmallKey");
    //删除大key
    redisTemplate.delete("HashKey");
    
    • 1
    • 2
    • 3
    • 4

    10)、判断Hash中是否含有该值

    Boolean isEmpty = redisTemplate.boundHashOps("HashKey").hasKey("SmallKey");
    
    • 1

    6、Set类型相关操作

    1)、添加Set缓存(值可以是一个,也可是多个)(2/3是1的递进值)

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2)、设置过期时间(单独设置)

    redisTemplate.boundValueOps("setKey").expire(1,TimeUnit.MINUTES);
    redisTemplate.expire("setKey",1,TimeUnit.MINUTES);
    
    • 1
    • 2

    3)、根据key获取Set中的所有值

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

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

    Boolean isEmpty = redisTemplate.boundSetOps("setKey").isMember("setValue2");
    
    • 1

    5)、获取Set缓存的长度

    Long size = redisTemplate.boundSetOps("setKey").size();
    
    • 1

    6)、移除指定的元素

    Long result1 = redisTemplate.boundSetOps("setKey").remove("setValue1");
    
    • 1

    7)、移除指定的key

    Boolean result2 = redisTemplate.delete("setKey");
    
    • 1

    7、 LIST类型相关操作

    1)、添加缓存(2/3是1的递进值)

    //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");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2)、将List放入缓存

    ArrayList<String> list = new ArrayList<>();
    redisTemplate.boundListOps("listKey").rightPushAll(list);
    redisTemplate.boundListOps("listKey").leftPushAll(list);
    
    • 1
    • 2
    • 3

    3)、设置过期时间(单独设置)

    redisTemplate.boundValueOps("listKey").expire(1,TimeUnit.MINUTES);
    redisTemplate.expire("listKey",1,TimeUnit.MINUTES);
    
    • 1
    • 2

    4)、获取List缓存全部内容(起始索引,结束索引)

    List listKey1 = redisTemplate.boundListOps("listKey").range(0, 10); 
    
    • 1

    5)、从左或从右弹出一个元素

    String listKey2 = (String) redisTemplate.boundListOps("listKey").leftPop();  
    //从左侧弹出一个元素
    String listKey3 = (String) redisTemplate.boundListOps("listKey").rightPop(); 
    //从右侧弹出一个元素
    
    • 1
    • 2
    • 3
    • 4

    6)、根据索引查询元素

    String listKey4 = (String) redisTemplate.boundListOps("listKey").index(1);
    
    • 1

    7)、获取List缓存的长度

    Long size = redisTemplate.boundListOps("listKey").size();
    
    • 1

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

    redisTemplate.boundListOps("listKey").set(3L,"listLeftValue3");
    
    • 1

    9)、移除N个值为value(key,移除个数,值)

    redisTemplate.boundListOps("listKey").remove(3L,"value");
    
    • 1

    8、Zset类型的相关操作

    1)、向集合中插入元素,并设置分数
    //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);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

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

    DefaultTypedTuple<String> p1 = new DefaultTypedTuple<>("zSetVaule1", 2.1D);
    DefaultTypedTuple<String> p2 = new DefaultTypedTuple<>("zSetVaule2", 3.3D);
    redisTemplate.boundZSetOps("zSetKey").add(new HashSet<>(Arrays.asList(p1,p2)));
    
    • 1
    • 2
    • 3

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

    Set<String> range = redisTemplate.boundZSetOps("zSetKey").range(0, -1);
    
    • 1

    4)、获得指定元素的分数

    Double score = redisTemplate.boundZSetOps("zSetKey").score("zSetVaule");
    
    • 1

    5)、返回集合内的成员个数

    Long size = redisTemplate.boundZSetOps("zSetKey").size();
    
    • 1

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

    Long COUNT = redisTemplate.boundZSetOps("zSetKey").count(0D, 2.2D);
    
    • 1

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

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

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

    Set<String> ranking2 = 
                       redisTemplate.opsForZSet().rangeByScore("zSetKey", 0D, 2.2D 1, 3);
    
    • 1
    • 2

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

    Set<TypedTuple<String>> tuples =                                                 redisTemplate.boundZSetOps("zSetKey").rangeWithScores(0L, 3L);
      for (TypedTuple<String> tuple : tuples) {
          System.out.println(tuple.getValue() + " : " + tuple.getScore());
      }
    
    • 1
    • 2
    • 3
    • 4

    10)、返回指定成员的排名

    //从小到大
    Long startRank = redisTemplate.boundZSetOps("zSetKey").rank("zSetVaule");
    //从大到小
    Long endRank = redisTemplate.boundZSetOps("zSetKey").reverseRank("zSetVaule");
    
    • 1
    • 2
    • 3
    • 4

    11)、从集合中删除指定元素

    redisTemplate.boundZSetOps("zSetKey").remove("zSetVaule");
    
    • 1

    12)、删除指定索引范围的元素(Long类型)

    redisTemplate.boundZSetOps("zSetKey").removeRange(0L,3L);
    
    • 1

    13)、删除指定分数范围内的元素(Double类型)

    redisTemplate.boundZSetOps("zSetKey").removeRangeByScorssse(0D,2.2D);
    
    • 1

    14)、为指定元素加分(Double类型)

    Double score = redisTemplate.boundZSetOps("zSetKey").incrementScore("zSetVaule",1.1D);
    
    • 1

    三、SpringBoot整合Redis—RedisTemplate

    1、引入依赖

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-redisartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    2、RedisTemplate五种数据结构的操作

    redisTemplate.opsForValue(); //操作字符串
    redisTemplate.opsForHash(); //操作hash
    redisTemplate.opsForList(); //操作list
    redisTemplate.opsForSet(); //操作set
    redisTemplate.opsForZSet(); //操作有序zset
    RedisTemplate方法讲解
    判断key是否存在
     /**
         * 判断key是否存在
         */
        @GetMapping("haskey")
        public boolean hasKey(String key) {
            return redisTemplate.hasKey(key);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3、获取指定的key的失效时间

     /**
         * 指定key的失效时间
         */
        @GetMapping("expire")
        public void expire(String key, long time) {
            //参数一:key
            //参数二:睡眠时间
            //参数三:睡眠时间单位 TimeUnit.DAYS 天 TimeUnit.HOURS 小时 。。。
            redisTemplate.expire(key, time, TimeUnit.MINUTES);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    4、key获取过期时间

    /**
         * 根据key获取过期时间
         */
        @GetMapping("getexpire")
        public long getExpire(String key) {
            Long expire = redisTemplate.getExpire(key);
            return expire;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    5、根据key删除reids中缓存数据

    /**
         * 根据key删除reids中缓存数据
         */
        @GetMapping("delredisbykey")
        public void delete(String key) {
            redisTemplate.delete(key);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    6、保存和读取String

    /**
         * 保存和读取String
         */
    @GetMapping("stringredisdemo")
    public String stringredisdemo() {
    	//设置过期时间为1分钟
        redisTemplate.opsForValue().set("key1", "value1", 1, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("key2", "value2");
        redisTemplate.opsForValue().set("key3", "value3");
        //读取redis数据
        String result1 = redisTemplate.opsForValue().get("key1").toString();
        String result2 = redisTemplate.opsForValue().get("key2").toString();
        String result3 = redisTemplate.opsForValue().get("key3").toString();
        System.out.println("缓存结果为:result:" + result1 + "  " + result2 + "   " + result3);
        return "缓存结果为:result:" + result1 + "  " + result2 + "   " + result3;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    7、保存和读取list

    /**
         * 保存和读取list
         */
    @GetMapping("listredisdemo")
    public String listredisdemo() {
        List<String> list1 = new ArrayList<>();
        list1.add("a1");
        list1.add("a2");
        list1.add("a3");
        List<String> list2 = new ArrayList<>();
        list2.add("b1");
        list2.add("b2");
        list2.add("b3");
        redisTemplate.opsForList().leftPush("listkey1", list1);
        redisTemplate.opsForList().rightPush("listkey2", list2);
        List<String> resultList1 = (List<String>) redisTemplate.opsForList().leftPop("listkey1");
        List<String> resultList2 = (List<String>) redisTemplate.opsForList().rightPop("listkey2");
        System.out.println("resultList1:" + resultList1);
        System.out.println("resultList2:" + resultList2);
        return "成功";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    8、Hash结构,保存和读取map

     /**
         * Hash结构,保存和读取map
         */
        @GetMapping("mapredisdemo")
        public String mapredisdemo() {
            Map<String, String> map = new HashMap<>();
            map.put("key1", "value1");
            map.put("key2", "value2");
            map.put("key3", "value3");
            map.put("key4", "value4");
            map.put("key5", "value5");
            redisTemplate.opsForHash().putAll("map1", map);
            Map<String, String> resultMap = redisTemplate.opsForHash().entries("map1");
            List<String> reslutMapList = redisTemplate.opsForHash().values("map1");
            Set<String> resultMapSet = redisTemplate.opsForHash().keys("map1");
            String value = (String) redisTemplate.opsForHash().get("map1", "key1");
            System.out.println("value:" + value);
            System.out.println("resultMapSet:" + resultMapSet);
            System.out.println("resultMap:" + resultMap);
            System.out.println("resulreslutMapListtMap:" + reslutMapList);
            return "成功";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    9、保存和读取Set

    /**
         * 保存和读取Set
         */
        @GetMapping("setredisdemo")
        public String getredisdemo() {
            SetOperations<String, String> set = redisTemplate.opsForSet();
            set.add("key1", "value1");
            set.add("key1", "value2");
            set.add("key1", "value3");
            Set<String> resultSet = redisTemplate.opsForSet().members("key1");
            System.out.println("resultSet:" + resultSet);
            return "resultSet:" + resultSet;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    10、保存和读取zset

    /**
         * 保存和读取zset
         */
        @GetMapping("zsetredisdemo")
        public String zsetredisdemo() {
            ZSetOperations.TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<>("zset-5", 9.6);
            ZSetOperations.TypedTuple<Object> objectTypedTuple2 = new DefaultTypedTuple<>("zset-6", 9.9);
            Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>();
            tuples.add(objectTypedTuple1);
            tuples.add(objectTypedTuple2);
            System.out.println(redisTemplate.opsForZSet().add("zset1", tuples));
            System.out.println(redisTemplate.opsForZSet().range("zset1", 0, -1));
            return "成功";
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    完整示例代码

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.DefaultTypedTuple;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.SetOperations;
    import org.springframework.data.redis.core.ZSetOperations;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.*;
    import java.util.concurrent.TimeUnit;
    
    @RestController
    public class ReidsDemo {
    
        @Autowired
        RedisTemplate redisTemplate;
    
        /**
         * 指定key的失效时间
         */
        @GetMapping("expire")
        public void expire(String key, long time) {
            //参数一:key
            //参数二:睡眠时间
            //参数三:睡眠时间单位 TimeUnit.DAYS 天 TimeUnit.HOURS 小时 。。。
            redisTemplate.expire(key, time, TimeUnit.MINUTES);
        }
    
        /**
         * 根据key获取过期时间
         */
        @GetMapping("getexpire")
        public long getExpire(String key) {
            Long expire = redisTemplate.getExpire(key);
            return expire;
        }
    
        /**
         * 判断key是否存在
         */
        @GetMapping("haskey")
        public boolean hasKey(String key) {
            return redisTemplate.hasKey(key);
        }
    
        /**
         * 根据key删除reids中缓存数据
         */
        @GetMapping("delredisbykey")
        public void delete(String key) {
            redisTemplate.delete(key);
        }
    
        /**
         * 保存和读取String
         */
        @GetMapping("stringredisdemo")
        public String stringredisdemo() {
            //设置过期时间为1分钟
            redisTemplate.opsForValue().set("key1", "value1", 1, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("key2", "value2");
            redisTemplate.opsForValue().set("key3", "value3");
            //读取redis数据
            String result1 = redisTemplate.opsForValue().get("key1").toString();
            String result2 = redisTemplate.opsForValue().get("key2").toString();
            String result3 = redisTemplate.opsForValue().get("key3").toString();
            System.out.println("缓存结果为:result:" + result1 + "  " + result2 + "   " + result3);
            return "缓存结果为:result:" + result1 + "  " + result2 + "   " + result3;
        }
    
        /**
         * 保存和读取list
         */
        @GetMapping("listredisdemo")
        public String listredisdemo() {
            List<String> list1 = new ArrayList<>();
            list1.add("a1");
            list1.add("a2");
            list1.add("a3");
            List<String> list2 = new ArrayList<>();
            list2.add("b1");
            list2.add("b2");
            list2.add("b3");
            redisTemplate.opsForList().leftPush("listkey1", list1);
            redisTemplate.opsForList().rightPush("listkey2", list2);
            List<String> resultList1 = (List<String>) redisTemplate.opsForList().leftPop("listkey1");
            List<String> resultList2 = (List<String>) redisTemplate.opsForList().rightPop("listkey2");
            System.out.println("resultList1:" + resultList1);
            System.out.println("resultList2:" + resultList2);
            return "成功";
        }
    
        /**
         * Hash结构,保存和读取map
         */
        @GetMapping("mapredisdemo")
        public String mapredisdemo() {
            Map<String, String> map = new HashMap<>();
            map.put("key1", "value1");
            map.put("key2", "value2");
            map.put("key3", "value3");
            redisTemplate.opsForHash().putAll("map1", map);
            Map<String, String> resultMap = redisTemplate.opsForHash().entries("map1");
            List<String> reslutMapList = redisTemplate.opsForHash().values("map1");
            Set<String> resultMapSet = redisTemplate.opsForHash().keys("map1");
            String value = (String) redisTemplate.opsForHash().get("map1", "key1");
            System.out.println("value:" + value);
            System.out.println("resultMapSet:" + resultMapSet);
            System.out.println("resultMap:" + resultMap);
            System.out.println("resulreslutMapListtMap:" + reslutMapList);
            return "成功";
        }
    
        /**
         * 保存和读取Set
         */
        @GetMapping("setredisdemo")
        public String getredisdemo() {
            SetOperations<String, String> set = redisTemplate.opsForSet();
            set.add("key1", "value1");
            set.add("key1", "value2");
            set.add("key1", "value3");
            Set<String> resultSet = redisTemplate.opsForSet().members("key1");
            System.out.println("resultSet:" + resultSet);
            return "resultSet:" + resultSet;
        }
    
        /**
         * 保存和读取zset
         */
        @GetMapping("zsetredisdemo")
        public String zsetredisdemo() {
            ZSetOperations.TypedTuple<Object> objectTypedTuple1 = new DefaultTypedTuple<>("zset-5", 9.6);
            ZSetOperations.TypedTuple<Object> objectTypedTuple2 = new DefaultTypedTuple<>("zset-6", 9.9);
            Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>();
            tuples.add(objectTypedTuple1);
            tuples.add(objectTypedTuple2);
            System.out.println(redisTemplate.opsForZSet().add("zset1", tuples));
            System.out.println(redisTemplate.opsForZSet().range("zset1", 0, -1));
            return "成功";
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143

    序列化

    直接粘贴在项目中即可

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    
    /*
    *序列化
     */
    @Configuration
    public class MyRedisConfig {
    
        @Bean(name = "redisTemplate")
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
            RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
            //参照StringRedisTemplate内部实现指定序列化器
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            redisTemplate.setKeySerializer(keySerializer());
            redisTemplate.setHashKeySerializer(keySerializer());
            redisTemplate.setValueSerializer(valueSerializer());
            redisTemplate.setHashValueSerializer(valueSerializer());
            return redisTemplate;
        }
    
        private RedisSerializer<String> keySerializer(){
            return new StringRedisSerializer();
        }
    
        //使用Jackson序列化器
        private RedisSerializer<Object> valueSerializer(){
            return new GenericJackson2JsonRedisSerializer();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    参考文章:

    Redis CSDN文档: https://blog.csdn.net/lydms/article/details/105224210

    文档2 springboot:https://ost.51cto.com/posts/2333

    Redis命令: http://doc.redisfans.com/

  • 相关阅读:
    业绩走低,毛利率下滑,海外市场能否成为极米科技救命稻草?
    Ubuntu 22.04.6 | QEMU KVM 安装 macOS虚拟机
    深入理解并发和并行
    python 将Excel导入到oracle
    [蓝桥杯2020初赛] 门牌制作与既约分数与蛇形填数
    css设置字体属性
    电脑微软账户登录一直转圈怎么解决问题
    Unity Xlua热更新框架(八):对象池
    如何开发你的第一个Vue.js插件:完整指南
    计算机毕业设计(30)java毕设作品之多用户B2C商城平台系统
  • 原文地址:https://blog.csdn.net/zhezhe_9860/article/details/126279143