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<Account> accountCacheContext;
 
    public Account getAccountByName(String accountName) {
        Account result = accountCacheContext.get(accountName);
        if (result != null) {
            logger.info("get from cache... {}", accountName);
            return result;
        }
 
        Optional<Account> 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<Account> 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:

Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理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.

Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理For the second query request issued by application, the cached result will be returned by Spring handler:

Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理Java注解@Cacheable的工作原理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.




上一篇:开放下载!《Apache RocketMQ 从入门到实战》


下一篇:Apache RocketMQ核心技术与实战 丨讲师文章合集