Implementing caching with @Cacheable in Spring 3.1

The use of caching in software development has a very long history. Cache is a good design idea, once you use it, you will find it really useful. The core of the Spring 3.1 version implements the cache. Before Java introduced the Annotation feature, a difficulty in implementing caching was that it was too coupled with business logic code.

However, the use of @Cacheable and @CacheEvict to implement caching in Spring 3.1 solves this problem to a certain extent. The basic idea is to add @Cacheable annotation to the method, and the return value of this method will have cache characteristics.

The @Cacheable annotation can be used at the method or class level. When it is applied at the method level, it is the cache return value as mentioned above. When applied at the class level, the return values ​​of all methods of this class will be cached.

@Cacheable(value = "employee")
public class EmployeeDAO {

  public Person findEmployee(String firstName, String surname, int age) {

    return new Person(firstName, surname, age);
  }

  public Person findAnotherEmployee(String firstName, String surname, int age) {

    return new Person(firstName, surname, age);
  }
}

The @Cacheable annotation has three parameters, the value is required, and the key and condition. The first parameter, value, specifies where the cache will be stored.

@Cacheable(value = "employee")
 public Person findEmployee(String firstName, String surname, int age) {

   return new Person(firstName, surname, age);
 }


The above code guarantees that the return value of findEmployee, the Person object will be stored in "employee".

Any data stored in the cache requires a key for high-speed access. Spring uses the signature of the method annotated with @Cacheable as the key by default. Of course, you can override the key, and you can use the SpEL expression to customize the key.

@Cacheable(value = "employee", key = "#surname")
   public Person findEmployeeBySurname(String firstName, String surname, int age) {

    return new Person(firstName, surname, age);
  }

In the annotation of findEmployeeBySurname() "#surname" is a SpEL expression that will use the surname parameter in the findEmployeeBySurname() method as the key.

The last parameter of @Cacheable is condition (optional), which again refers to a SpEL expression. But this parameter will indicate whether the return result of the method is cached.

@Cacheable(value = "employee", condition = "#age < 25")
 public Person findEmployeeByAge(String firstName, String surname, int age) {

   return new Person(firstName, surname, age);
 }


In the above example, only if the age is less than 25 will be cached.

After a quick look at how to use the cache, let's take a look at the effect of the cache.

<A href="http://my.oschina.net/test45" target=_blank rel=nofollow>@Test</A>
  public void testCache() {

    Person employee1 = instance.findEmployee("John", "Smith", 33);
    Person employee2 = instance.findEmployee("John", "Smith", 33);

    assertEquals(employee1, employee2);
  }

The above example is very simple. The first time findEmployee is called, the findEmployee method will be executed, and Spring will store its return value as a person object in the cache. The second time findEmployee is called, findEmployee will not be executed, and Spring will directly return the data in the cache as the return value. So employee1 and employee2 refer to the same object.


In the following example, we use the age less than 25 as the cache condition, and we will get different results.

<A href="http://my.oschina.net/test45" target=_blank rel=nofollow>@Test</A>
 public void testCacheWithAgeAsCondition() {

   Person employee1 = instance.findEmployeeByAge("John", "Smith", 33);
   Person employee2 = instance.findEmployeeByAge("John", "Smith", 33);

   assertEquals(employee1, employee2);
 }


In the following example, we customize the key in the annotation of the findEmployeeBySurname method. We use a custom key generation method to ensure that different surnames will point to different people. see the program below

<A href="http://my.oschina.net/test45" target=_blank rel=nofollow>@Test</A>
 public void testCacheOnSurnameAsKey() {

   Person employee1 = instance.findEmployeeBySurname("John", "Smith", 22);
   Person employee2 = instance.findEmployeeBySurname("Jack", "Smith", 55);

   assertEquals(employee1, employee2);
 }

We want to find two different people, but the surname of the two people is the same, you will find that the two calls return the same result, this is not a problem with Spring, but a problem with the way our cache key is generated. So when we define the key, we must pay attention to the key generation strategy to avoid this problem.

Finally, to summarize the process, when a method annotated with @Cacheable is executed, Spring first checks whether the condition is satisfied. If not, executes the method and returns; if it is satisfied, it searches the cache space named by value to store the data stored by key. If the object is found, the result will be returned. If the execution method is not found, the return value of the method will be stored in the value cache in the form of a key-object, and then the method will return.

The above is just the usage of @Cacheable, but how do we use the @CacheEvict annotation to clear the cache? In addition, there is a question, how to choose a cache implementation and configure Spring's cache?

@Cacheable: When a method is called repeatedly with the same parameters, the method itself will not be called and executed, that is, the method itself will be skipped, and instead the result of the method will be found and returned directly from the cache.
@CachePut: This annotation ensures that the method is executed and the return value of the method is also recorded in the cache.

@cachePut is equivalent to the Update() operation. As long as the method marked by it is called, it will be cached, while @cache will first check whether it has been cached, and then choose whether to execute the method. @CacheEvict is equivalent to the Delete() operation. Used to clear the cache.


@CacheEvict main parameters


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326864829&siteId=291194637