同步多线程以确保只有其中一个线程缓存结果(使用 spring 缓存)?

Synchronize multiple-threads to ensure only one of them caches a result (using spring cache)?

假设我有一个方法A,它是@Cacheable,但是很多线程可能同时使用相同的参数访问它。

我想确保只有第一个线程创建缓存,以防止所有其他线程处理它们的请求。

我当然可以使用synchronized来包装这个方法。但这会导致所有线程都阻塞在该方法上。而且,synchronized 不会包装 @Cacheable AOP。

那么,有没有一种使用 Spring 开箱即用的方法来实现这个?

参见 @Cacheable 注释 sync 属性(Javadoc) and Reference Documentation 相同。

此外,正如 @dnault 所暗示的,它也依赖于缓存提供程序的实现。并非所有缓存提供商都支持此选项,因此请检查您的缓存提供商是否支持。

关于...

"I'd like to ensure that only the first thread creates the cache, to prevent all of the other thread from processing their requests."

缓存同步不是同步“缓存本身的创建”,而是同步缓存的条目(按键)。

缓存是 Map(即 key/value store/data 结构)。

如果我有一个有利于缓存的应用服务方法,例如:

@Service
class UserService {


  @Cacheable(cacheNames = "UsersByName", sync = true)
  User findBy(String name) {
    ...
  }
}

那么如果给出...

Thread A: userService.findBy("janeDoe");

Thread B: userService.findBy("jonDoe");

Thread C: usesService.findBy("janeDoe");

只有线程C会阻塞并等待线程A.

计算的缓存结果

线程 B 将不间断地继续查找或计算“jonDoe”的 User

另请注意,大多数缓存提供程序都希望“UsersByName”缓存在应用程序 configuration/startup 时已经存在。