问题
I have two functions:
First, whenever user asks for a value based on key, i search the database and store the result in cache for faster future references. @Cacheable notation helped me in achieving this.
Second, whenever user wants to update the value, instead of directly doing the db update operation, I want to update the cache and use a scheduled task to later update the db. I used @CachePut for this.
@Cacheable(key="#id")
public String getDoc(String id){
// fetch value from database
return val; // will store value in cache
}
@CachePut(key="#id")
public String setDoc(String id, String newVal){
return newVal; // will update value in cache
}
Now in a multi-threaded environment, if multiple users try to update the same value in cache, it might lead to race condition which i want to prevent.
My aim is to synchronize the below mentioned flow
Call getDoc(id) to get existing value
Perform some calculations to modify the value
Call setDoc(id, newVal) to update the value
I want the lock to be achieved only if the users are updating the same record, so I cannot synchronize the above flow by putting it in a synchronized block. I read about sync=true
attribute for @Cacheable annotation, but it doesn't work with @CachePut.
Can someone please suggest an approach to achieve this?
来源:https://stackoverflow.com/questions/61934910/synchronizing-spring-cache-based-on-record-id