RedisTemplate通过scan方法进行自定义操作:1、根据hashKey的名称匹配相关hash键值对

需求:有一个hash如下,现在想查询出stream前缀的键值对

 操作方法如下:

package com.example;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Map;
import java.util.TreeMap;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestHash {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testScan()
    {
        Cursor<Map.Entry<String, String>> cursor = redisTemplate.opsForHash().scan(
                "media.9f2ef88f-c7b2-4325-8d64-ba03a9278516",
                ScanOptions.scanOptions().match("stream*.ts").build()); //此处使用表达式和键名进行匹配

        TreeMap<String,byte[]> streaming = new TreeMap<>();

        while (cursor.hasNext())
        {
            Map.Entry<String, String> entry = cursor.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.printf("%s %s
",key,value);
        }

    }   
}

结果:

原文地址:https://www.cnblogs.com/passedbylove/p/12020988.html