redis模板有查询语言吗?

Does redis template have a query language?

redis模板有查询语言吗?。假设我在 redis 缓存中有一个这样存储的列表: 核心价值 我的列表 -> [1,2,3,4,5]

我想获取列表中符合特定条件的值。我们可以用 redis 模板来做吗?

你应该使用redis 命令'sort' 来填写要求。你可以参考 here。在 spring 中,您使用 SortQueryBuilder 来映射此命令。 myList是redis中存储[1,2,3,4,5]的key。

  1. 定义一个 redisTemplate bean
    
    @Bean(name="myRedisTemplate")
    public RedisTemplate myRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(stringRedisSerializer);

        return template;
    }
  1. 在服务中 class 自动装配了这个 bean
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.query.SortQuery;
import org.springframework.data.redis.core.query.SortQueryBuilder;
import org.springframework.data.redis.connection.SortParameters;

@Service
public class MyService{

       @Autowired
    private RedisTemplate myRedisTemplate;

      public void find(){

        // >=3
        SortQuery<String> sortQuery = SortQueryBuilder.sort("myList").order(SortParameters.Order.ASC).limit(2,-1).build();
        List<String> sortRslt = myRedisTemplate.sort(sortQuery);
        for(String s : sortRslt) {
            System.out.print(s+" ");
        }
        System.out.print("\n");

        // >3
        sortQuery = SortQueryBuilder.sort("myList").order(SortParameters.Order.ASC).limit(3,-1).build();
        sortRslt = myRedisTemplate.sort(sortQuery);
        for(String s : sortRslt) {
            System.out.print(s+" ");
        }
        System.out.print("\n");

        // >2 && < 5
        sortQuery = SortQueryBuilder.sort("myList").order(SortParameters.Order.ASC).limit(2,2).build();
        sortRslt = myRedisTemplate.sort(sortQuery);
        for(String s : sortRslt) {
            System.out.print(s+" ");
        }
        System.out.print("\n");
    }

如果查询字符串,您应该将数据类型从列表更改为集合。然后使用带有匹配模式参数的 'sscan' 命令来完成它。

例如,名为 mySet 的集合中有 {'abc'、'hello'、'follow'、'five'、'beijing'}。并且您想查找以 f.

开头的字符串
        ScanOptions options = ScanOptions.scanOptions().match("f*").count(1).build();
        try (Cursor<String> cursor = myRedisTemplate.boundSetOps("mySet").scan(options)){
            while (cursor.hasNext()) {
                String value = cursor.next();
                System.out.println("value is " + value);
            }
        }catch(Exception ex){
        }