Synchronizing Spring cache based on record id

偶尔善良 提交于 2020-06-16 23:42:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!