并发调用缓存的方法 [英] Concurrent calls to cached method

查看:109
本文介绍了并发调用缓存的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有Guava缓存的Spring缓存抽象. 我有一个带有@Cacheable批注和参数(用作缓存键)的方法,可将值放入缓存. 但是,此方法是在多线程环境中访问的,因此,具有相同参数值的对该方法有多个并发调用. 因此,这意味着对同一缓存键多次执行创建要缓存的值的逻辑,并同时将其多次放入缓存. 如果对于每个参数值(缓存键)该方法仅被调用一次并放入缓存一次,则效率会更高. Spring可以处理这种情况吗?

I'm using Spring cache abstraction with Guava cache. I have a method with @Cacheable annotation and parameter (that serves as a cache key) to put values into the cache. But this method is accessed in a multi threaded env so there are multiple concurrent calls to the method with the same parameter value. So that means the same logic that creates the value to be cached is done for the same cache key multiple times and put into the cache multiple times concurrently. It'd be much more efficient if for each parameter value (cache key) the method would be called only once and put into the cache once. Can Spring handle such a scenario?

推荐答案

从Spring Framework 4.3开始(在撰写本文时仍处于早期开发阶段),在@Cacheable上的名为sync的新标记可用.如果启用该标志,则基本上可以选择要问的内容.

As of Spring Framework 4.3 (still in early development phase at the time of writing) a new flag on @Cacheable called sync is available. If you enable that flag, you opt-in for basically what you're asking.

Spring Framework 4.3 GA将于明年5月左右发布,但您仍然应该在2016年第一季度看到第一个里程碑.请尝试一下,让我们知道是否适合您.

Spring Framework 4.3 GA is due around May next year but you should see a first milestone in Q1 2016 still. Please give that a try and let us know if that works for you.

这篇关于并发调用缓存的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆