admin管理员组

文章数量:1202350

I'm trying to add a caching layer to my persistence layer using the built-in @Cacheable annotation. However, I have a method that returns results as a list.

@Cacheable(value = "bookings", keyGenerator = "userIdListKeyGenerator")
List<Booking> findAllByUserIdsIn(List<Long> userIds) {
    return _repository.findAllByUserIdsIn(userIds);
}

Scenario: Let's say we first query the data with userIds = [1, 2, 3]. In this case, Spring will create a key-value pair in Redis that might look like this:

user-ids-1,2,3 : [Booking(1), Booking(2), Booking(3)]

Now, if we query with userIds = [2, 3], Spring will create another key-value pair:

user-ids-2,3 : [Booking(2), Booking(3)]

As you can see, there is a lot of data duplication. I want to optimize this by storing each Booking per userId as a separate key-value pair, so the Redis structure would look like this:

user-id-1: Booking(1)
user-id-2: Booking(2)
user-id-3: Booking(3)

This way, when we need to retrieve the cached data, we could use something like RedisTemplate#opsForValue#multiGet to get multiple key-value pairs at once.

While I could implement my own caching logic using RedisTemplate, I'm wondering if it's possible to achieve this behavior using the built-in @Cacheable annotation.

本文标签: javaHow do I optimizing caching with Cacheable to avoid data duplication in RedisStack Overflow