Skip to content
Advertisement

Spring data redis – How to use hashOperation’s scan method to get keys or values based on pattern?

I have never worked on Redis and Spring boot. I want to use Redis as a cache.

I have been using hashOperations for get/set operations. I have configured the RedisTemplate to stop weird hashes from getting prepended to a key.

I have a class called Post which I am caching. A user can create multiple posts. The key gets generated like this : userId::postId and the post data gets cached.

How to use scan method of RedisTemplate to get all posts of a particular user? I tried ScanOptions and the pattern * but I am certainly doing something wrong as I am not getting any data. There aren’t many links or youtube videos on scan and ScanOptions so I am finding it difficult to implement.

This is what I have wrote for getting all posts of a user:

public List<Post> getPostsByUid(String uid) {
    String key = uid + "::";
    ScanOptions scanOptions = ScanOptions.scanOptions().match("*").count(20).build();
    Cursor cursor = hashOperations.scan(key, scanOptions);
    List<Post> posts = new ArrayList<>();
    while(cursor.hasNext()) {
        posts.add((Post)cursor.next());
    }
    return posts;
}

This is the savePost method

public Post savePost(Post post) {
    String key = post.getUid() + "::" + post.getPostid();
    hashOperations.put(key, "", post);
    return post;
}

Thanks for helping!

Advertisement

Answer

hashOperations.scan scans within a hash. But you want to scan within whole database (Redis).

String keyPattern = uid + "::" + "*";
ScanOptions scanOptions = ScanOptions.scanOptions().match(keyPattern).count(20).build();
Cursor c = redisConnection.scan(options); // scanning in db
while (c.hasNext()) {
    // c.next() is Redis key. Use this in hashOperations to get your Post.
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement