0

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!

asked May 2, 2021 at 13:30

1 Answer 1

1

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.
}
answered May 3, 2021 at 7:41
Sign up to request clarification or add additional context in comments.

3 Comments

Can we use hashOperations when Redis is used as a cache or is it only used when Redis is used as a database?
Always. hashOperations just means the operations will be done on Redis hash data structure.
how can i inject redisConnection? thanks

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.