cacheable注解原理_Java注解@Cacheable的工作原理

In order to avoid unnecessary query on database it is a common pattern to define a cache in application layer to cache the query result from database. See one example below. Here the application cache is maintained in a custom class CacheContext.

public class AccountService1 {

private final Logger logger = LoggerFactory.getLogger(AccountService1.class);

private CacheContext accountCacheContext;

public Account getAccountByName(String accountName) {

Account result = accountCacheContext.get(accountName);

if (result != null) {

logger.info("get from cache... {}", accountName);

return result;

}

Optional accountOptional = getFromDB(accountName);

if (!accountOptional.isPresent()) {

throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));

}

Account account = accountOptional.get();

accountCacheContext.addOrUpdateCache(accountName, account);

return account;

}

In Spring there is an annotation @Cacheable which can make the cache managed by Spring instead of application developer. See improved version:

public class AccountService2 {

private final Logger logger = LoggerFactory.getLogger(AccountService2.class);

@Cacheable(value="accountCache")

public Account getAccountByName(String accountName) {

logger.info("in method getAccountByName, querying account... {}", accountName);

Optional accountOptional = getFromDB(accountName);

if (!accountOptional.isPresent()) {

throw new IllegalStateException(String.format("can not find account by account name : [%s]", accountName));

}

return accountOptional.get();

}

In this example, there is no more cache evaluation and cache fill logic. All such stuff are taken over by Spring under the hood and completely transparent to application developer, with the help of following bean configuration in xml:

class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">

class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">

And how to research what magic has been done by Spring to achieve this behavior?

We use the following code to research. It is expected that the request sent by line 31 will directly reach database, while the second request in line 34 will be handled by Spring cache handler.

819cb4631ce03cfc7a95626531da709c.png

Here in line 31, in debugger we can find that accountService2 is not an instance of application class com.sap.AccountService2, but a dynamic proxy class generated by Spring.

850ac47a00819bf6a433a0fe86bf75dd.png

As a result after pressing F5, the intercept method of this dynamic proxy class is called:

f7c04d17dc2d59ad3d524d8c7dff9022.png

In this method, the execution will be delegated to Spring cache handler class:

e6872a47f0d83e95b3134e6d7d8cd1a1.png

76e5eb7b78cbcbbe1bc0db8911badc8e.png

In example 1, the logic of cache evaluation and fill is done by application, and now it is done in method execute below.

3c78e11cacbc3d6824c27414e032b07c.png

First internal cache managed by Spring is checked in line 336 via method findCachedItem. Due to expected cache miss, our application method will be called as usual via reflection, as demonstrated below:

b74605b1e4ab0ce5526f33548c21b91e.png

After application method to retrieve account from database is done, the result, Account instance with id 2495 is filled to Spring cache, the variable contexts below.

eecccfb7bc8c33c5c5a694bc6ae70407.png

Below is the screenshot for Spring internal cache to store application data, which is based on ConcurrentHashMap. Our cached Account instance with id 2495 could be found there.

35cb36f4273d94efb2e2df45cacddb35.png

b9c10c250a403aa5a6c634b8ab99ad55.png

For the second query request issued by application, the cached result will be returned by Spring handler:

e2843e830893978216ddadb87b20d1e3.png

The last question is, how and when the dynamic proxy is generated?

Again let’s go to the entry point of Beans initialization:

17ca6d84565e51716d59c7990b63713d.png

6be31d51fd249898ab0f983fd7d1794f.png

Here the dynamic proxy is created based on configuration defined in xml with the help of CGlibAopProxy. For more detail about CGlibAopProxy, please refer to Spring official document.

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

61fb9822a20bf853fa7bc619689492cf.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值