The reason why cacheable doesn’t work

Time:2021-7-8

Question scenario:

There are method a and method B in a class. When method a is called, the database will be called every time. Not in line with expectations.

/**
     *Method a 
     */
    public Manager info() {
        return info(ManagerHelper.getManagerId());
    }

    /**
     *Method B
     */
    @Cacheable(key = "#id")
    public Manager info(Long id) {
        return managerRepository.findById(id).orElseThrow(EntityExistsException::new);
    }

Cause of the problem:

Spring cache annotation is based on the aspect of spring AOP, and it can only take effect through proxy. When a method with cache annotation is called by the same class or a subclass, it belongs to internal call, so the annotation does not take effect because there is no proxy.

resolvent:

Method 1: extract the cached method into a separate class, and then call it in the implementation class of service;

Method 2: manually use the cache manager to get the cache effect.

Conclusion:

  • Using annotations@CacheableThe object of must be a bean managed by spring.
  • The caller must be another method.

Annotated caching does not work when:

For the same bean internal method call, the subclass calls the method with cache annotation in the parent class

Recommended Today

Implementation example of go operation etcd

etcdIt is an open-source, distributed key value pair data storage system, which provides shared configuration, service registration and discovery. This paper mainly introduces the installation and use of etcd. Etcdetcd introduction etcdIt is an open source and highly available distributed key value storage system developed with go language, which can be used to configure sharing […]