Guava cache, one to many key-values

90 Views Asked by At

This is my first time posting a question here,and I'm new to Guava Cache, so please bare with me :).

Regarding the cache keys - In the DB itself the relation between my key to the values I'm extracting is one-to-many.

Let's say I have the following scenario when my cache is configured as <String, List> - Looking for "key1".

In a given cache state I have:

"key1" -> (val1, val2, val3,...).

And in the DB I have in addition:

 "key1" - val4, "key1" - val5.

Now, as I understand it, only if the LoadingCache will notice there's a missing key it'll query the db. So in this scenario It won't load the missing values I need, as it sees the keys in the cache - resulting in missing data loading.

1

There are 1 best solutions below

2
MrCrobben On

You can add refreshAfterWrite to the cache builder so it automatically refreshes the cache after certain time period.

 LoadingCache<String, List<String>> cache = CacheBuilder.newBuilder()
            .refreshAfterWrite(5, TimeUnit.MINUTES) // Set a refresh interval, e.g., every 5 minutes
            .build(new CacheLoader<String, List<String>>() {
                @Override
                public List<String> load(String key) {
                    // Load the list of values for the given key from the database
                    List<String> valuesFromDB = loadValuesFromDB(key);

                    // Return the loaded values
                    return valuesFromDB;
                }
 });

But the best option would be if you have access to the part of code that does value update in DB to update the cache after it.