Redis cache strategy for MySql with Spring Cache

668 views Asked by At

Currently I'm using Redis for following purpose:

  1. Cache web pages.
  2. Cache SQL query resulting in single result.

For example:

@Cacheable(value = "memberCache", key = "#username.concat('')")
public MemberModel findByUsername(String username) {
    return memMapper.findByUsername(username);
}

But the problem is how to cache SQL query resulting in multiple results.

e.g.:

public List<MemberModel> findWhichAgeBiggerThan(int age) {
    return memMapper.ageBiggerThan(age);
}

Now the result turns out to become a List. Of course I can cache this result too, but if a new user just registers to system, the result of this query might be changed. If this happens, cache will be stale. How to solve problems like this?

Thank you pretty pretty much!

1

There are 1 answers

0
Santosh Joshi On

Instead of using List you can use Redis Hash :

Your Method will be like this:

public Map<String, MemberModel> findWhichAgeBiggerThan(int age) {
   // return map with key as String(may be user id) and actual MemberModel
}

This whole map can be saved against a super key say "members" and individual data can be saved with student1, student2 keys as below

hset members student1 MemberModel1 student2 MemberModel2

To Add any other data simply use the above command with that paricular data like

hset members student_new MemberModel_new

here members will add/update the existing "nembers" key with the new data.