RedisTemplate使用

RedisTemplate使用

String类型

    @Override
    public void testString() {
        // t11();
        String key = "k1";
        String currentNum;
        // 用法1:key是否存在
        Boolean value = client.hasKey(key);
        log.info("[{}]是否存在[{}]", key, value);
        // 用法2:添加元素
        client.opsForValue().set(key, "v1", DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        // 用法3:获取元素
        String getValue = client.opsForValue().get(key);
        log.info("getValue : [{}]", getValue);
        // 用法4:计数
        String counter = "counter:key";
        client.opsForValue().set(counter, "0", DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        client.opsForValue().increment(counter);
        client.opsForValue().increment(counter);
        currentNum = client.opsForValue().get(counter);
        log.info("currentNum : [{}]", currentNum);
        client.opsForValue().decrement(counter);
        currentNum = client.opsForValue().get(counter);
        log.info("currentNum : [{}]", currentNum);

        // 用法5:存储list<map>结构数据
        List<Map<String, String>> multiMapList = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            LinkedHashMap<String, String> itemMap = Maps.newLinkedHashMap();
            itemMap.put("name", "jack" + i);
            if (i % 2 == 0) {
                itemMap.put("age", String.valueOf(10 + i));
                itemMap.put("sex", "男");
            } else {
                itemMap.put("age", String.valueOf(11 + i));
                itemMap.put("sex", "女");
            }
            multiMapList.add(itemMap);
        }
        String multiMapStr = JSON.toJSONString(multiMapList);
        client.opsForValue().set("str:multiusers", multiMapStr, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        String userList = client.opsForValue().get("str:multiusers");
        List<Map<String, String>> maps = CastBeanUtil.castListMap(JSON.parse(userList), String.class, String.class);
        log.info("maps : [{}]", maps);

        // 用法6:存储list<entity>
        List<TzArea> areaList = Lists.newArrayList();
        for (int i = 0; i < 10; i++) {
            TzArea item = new TzArea();
            item.setAreaId((long) i);
            item.setAreaName("江苏省");
            item.setLevel(1);
            item.setParentId(1L);
            areaList.add(item);
        }

        client.opsForValue().set("str:multiareas", JSON.toJSONString(areaList), DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        String res = client.opsForValue().get("str:multiareas");
        List<TzArea> tzAreas = JSON.parseArray(res, TzArea.class);
        log.info("tzAreas : [{}]", JSON.toJSONString(tzAreas));


    }

Hash类型

@Override
    public void testHash() {
        // 用法1:添加一个字段
        client.opsForHash().put("hash:user:single", "name", "pmb");
        client.expire("user", DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        Map<Object, Object> result = client.opsForHash().entries("hash:user:single");
        log.info("result : [{}]", result);
        // 用法2:添加一个对象信息
        Map<Object, Object> handleMap = Maps.newLinkedHashMap();
        handleMap.put("name", "jack");
        handleMap.put("age", "18");
        handleMap.put("sex", "男");
        String key = "hash:user:all";
        client.opsForHash().putAll(key, handleMap);
        Map<Object, Object> allElements = client.opsForHash().entries(key);
        log.info("allElements : [{}]", allElements);
        // 用法3:只获取map中key集合
        Set<Object> keyList = client.opsForHash().keys(key);
        log.info("keyList : [{}]", keyList);
        // 用法4:只获取map中value集合
        List<Object> valueList = client.opsForHash().values(key);
        log.info("valueList : [{}]", valueList);
    }

List类型


    @Override
    public void testList() {
        // 用法1:顺序添 加元素1,2,3,4
        // rightPush 列表右侧添加元素
        String key = "list:phoneList";
        client.opsForList().rightPush(key, "16607024161");
        client.opsForList().rightPush(key, "16607024162");
        client.opsForList().rightPush(key, "16607024163");
        client.expire(key, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        // 删除元素
        client.opsForList().rightPop(key);
        // 元素个数
        Long size = client.opsForList().size(key);
        assert size !=null;
        log.info(SIZE_FORMAT, size);
        // 查找元素
        // index 查找指定下标的元素 下标从0开始,最后一个size-1
        String firstItem = client.opsForList().index(key, 0);
        log.info("firstItem : [{}]", firstItem);
        String secondItem = client.opsForList().index(key, 1);
        log.info("secondItem : [{}]", secondItem);
        String thirdItem = client.opsForList().index(key, 2);
        log.info("thirdItem : [{}]", thirdItem);
        // list中所有元素
        List<String> res = client.opsForList().range(key, 0, size - 1);
        log.info("res : [{}]", res);
        // 修改制定位置数据
        client.opsForList().set(key, 0, "12");
        // 实现栈 先进后出
        client.opsForList().leftPush(key, "1");
        client.opsForList().leftPush(key, "2");
        client.opsForList().leftPush(key, "3");
        client.opsForList().leftPop(key);
        client.opsForList().leftPop(key);
        client.opsForList().leftPop(key);
       
        // 实现队列 先进先出
        client.opsForList().leftPush(key, "one");
        client.opsForList().leftPush(key, "two");
        client.opsForList().rightPop(key);
        client.opsForList().rightPop(key);
    }

Set类型

   @Override
    public void testSet() {
        String key = "set:nums";
        // 用法1:添加元素
        client.opsForSet().add(key, "1", "2", "3");
        client.expire(key, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        //用法2:获取集合的元素
        Set<String> members = client.opsForSet().members(key);
        log.info("members : [{}]", members);
        // 用法3:判断某个元素是否存在
        Boolean member = client.opsForSet().isMember(key, "2");
        log.info("member : [{}]", member);
        String intersection = "set:nums:intersection";
        // 用法4:交集
        client.opsForSet().add(intersection, "1", "2");
        client.expire(intersection, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        Set<String> intersectList = client.opsForSet().intersect(key, intersection);
        log.info("intersectList : [{}]", intersectList);
        // 用法5:并集
        Set<String> unionList = client.opsForSet().union(key, intersection);
        log.info("unionList : [{}]", unionList);
        // 用法6:查集
        Set<String> differenceList = client.opsForSet().difference(key, intersection);
        log.info("differenceList : [{}]", differenceList);


    }

Zset类型

  @Override
    public void testZset() {
        String key = "zset:nums";
        // 用法1:添加元素
        client.opsForZSet().add(key, "one", 1);
        client.opsForZSet().add(key, "three", 30);
        client.opsForZSet().add(key, "two", 20);
        client.opsForZSet().add(key, "four", 44);
        client.opsForZSet().add(key, "five", 55);
        client.expire(key, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        // 用法2:返回指定元素排名
        Long one = client.opsForZSet().rank(key, "five");
        log.info("rank : [{}]", one);
        Long size = client.opsForZSet().size(key);
        assert size !=null;
        log.info(SIZE_FORMAT, size);
        // 用法3:返回指定区间元素
        Set<String> range = client.opsForZSet().range(key, 0, size - 1);
        log.info("range : [{}]", range);
        // 用法4:指定分数区间用户
        Set<String> userList = client.opsForZSet().rangeByScore(key, 1, 60);
        log.info("userList : [{}]", userList);
        // 用法5:移除一个或者多个元素
        client.opsForZSet().remove(key, "two");
        log.info(SIZE_FORMAT, client.opsForZSet().size(key));
        // 用法6:计算指定分数之间用户个数
        Long count = client.opsForZSet().count(key, 1, 20);
        log.info("count : [{}]", count);
        Set<String> invertedOrder = client.opsForZSet().reverseRange(key, 0, -1);
        log.info("InvertedOrder : [{}]", invertedOrder);
        // 用法7:显示所有成员score以及对应用户
        Set<ZSetOperations.TypedTuple<String>> allLis = client.opsForZSet().rangeWithScores(key, 0, -1);
        assert allLis != null;
        for (ZSetOperations.TypedTuple<String> next : allLis) {
            String value = next.getValue();
            Double score = next.getScore();
            log.info("通过rangeWithScores(K key, long start, long end)方法获取RedisZSetCommands.Tuples的区间值:[{}],[{}]", value, score);
        }

        // 用法8:相同score返回处理,取值第一个
        String lexKey = "zset:lex";
        client.delete(lexKey);
        client.opsForZSet().add(lexKey, "zs", 55);
        client.opsForZSet().add(lexKey, "ls", 55);
        client.opsForZSet().add(lexKey, "ww", 54);
        client.opsForZSet().add(lexKey, "zl", 55);
        client.expire(lexKey, DateConstant.TIME_OF_DAY, TimeUnit.SECONDS);
        // 取出score集合
        Set<ZSetOperations.TypedTuple<String>> typedTuples = client.opsForZSet().rangeWithScores(lexKey, 0, -1);
        if(Objects.isNull(typedTuples)){
            throw new IllegalArgumentException("出现异常了");
        }
        Map<String, Double> cachedMap = new ConcurrentHashMap<>(16);
        Iterator<ZSetOperations.TypedTuple<String>> scoreIterator = typedTuples.iterator();
        String firstUser = null;
        while (scoreIterator.hasNext()) {
            ZSetOperations.TypedTuple<String> item = scoreIterator.next();
            Double score = item.getScore();
            String value = item.getValue();
            if (cachedMap.containsValue(score)) {
                // 找到重复score
                firstUser = value;
            }
            cachedMap.put(value, score);
        }
        log.info("firstUser : [{}]", firstUser);

       
    }

Redistemplate 是一个基于 Redis 的 Java 模板库,可以帮助开发者快速构建 Redis 应用程序。它提供了一组简单易用的 API,包括缓存、计数器、队列、分布式锁等功能。 使用 Redistemplate 需要以下步骤: 1. 引入依赖 在 Maven 或 Gradle 中引入 Redistemplate 的依赖,如下所示: Maven: ``` <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.5.5</version> </dependency> ``` Gradle: ``` implementation 'org.springframework.data:spring-data-redis:2.5.5' ``` 2. 配置 RedisTemplate 在 Spring 的配置文件中配置 RedisTemplate,如下所示: ``` @Configuration public class RedisConfig { @Bean public RedisConnectionFactory redisConnectionFactory() { return new JedisConnectionFactory(); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(new JdkSerializationRedisSerializer()); return template; } } ``` 3. 使用 Redistemplate 在代码中使用 Redistemplate,如下所示: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 以上代码就实现了一个简单的缓存操作,可以通过 set 方法设置缓存,通过 get 方法获取缓存。除此之外,Redistemplate 还提供了很多其他的 API,可以根据具体需求进行使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值