如何在 Redis 缓存的列表中按元素值进行搜索?

3
我们正在使用redis缓存,并存储以下示例类型的数据。
LLPUSH mylist "abc" "xyx" "awe" "wwqw"

现在我想从Spring项目中搜索Redis。例如,我的Spring项目类从某个外部客户端接收一个元素“abc”。如何按值搜索Redis列表?类似下面的内容:

现在我想从Spring项目中搜索Redis。例如,我的Spring项目类从某个外部客户端接收一个元素"abc",如何按照值搜索Redis列表?就像下面的例子一样:
ListOperations<String, Object> listOperations = redisTemplate.opsForList();

listOperations.get(key,"abc"); // returns abc

或者至少我想确认这个元素是否存在于 Redis 缓存列表中:

listOperations.contains(key, "abc"); // returns either true or false, based on the value presence

有没有类似的客户端库可以在Java端使用,以便在Spring Boot项目中使用Redis?请给出建议。

看看这个链接,也许对你有帮助:https://projects.spring.io/spring-data-redis/ - Rahul Dhande
我已经验证了spring-data-redis项目,其中redisTemplate有opsForList,在其中没有我需要的方法,就像我在问题中解释的那样。 - Bravo
3个回答

2
Redis的列表是由链表实现的。
  • Hence, you will either have to get all elements of the list using LRANGE and iterate to find a particular element.
  • If the list does not contain multiple entries and the order is not relevant, we can use LREM to remove the particular element and if there is a difference in list size, the element exists. Later, the removed element can be re-inserted if exists.

    Long initialSize = redisTemplate.opsForList().size(key);
    redisTemplate.opsForList().remove(key,0, value);
    Long finalSize = redisTemplate.opsForList().size(key);
    if(finalSize - initialSize > 0){
        redisTemplate.opsForList().rightPush(key,value);
        return true;     //Element exists
    }
    return false;    //Does not exist
    
考虑将操作原子化
您可以从这里获取其他Spring Redis列表操作。

1
你可以使用 Redis Set,其中包含 sismember(keyForSet,valueToSearch) 通过值搜索元素并具有 O(1) 的复杂度,这是非常高效的方法。为了与 redisTemplate 一起使用,你可以使用 redisTemplate.opsForSet.isMember(keyForSet,valueToSearch)
在插入时,你可以像这样插入列表:
jedis.sadd(keyForSet, myList.toArray(new String[myList.size()]));
或者使用 redisTemplate: redisTemplate.opsForSet.add(keyForSet, myList.toArray(new String[myList.size()]));

0

您可以使用Redisson Redis客户端和基于Redis的List对象轻松完成此操作:

List<String> list = redisson.getList("myList");

list.add("aaa");
list.add("bbb");
list.add("ccc");

// returns true
list.contains("aaa");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接