Spring cache annotations @CachePut, @CacheEvict, @CacheConfig are used

Links to the original text: https://www.cnblogs.com/OnlyCT/p/7845660.html#t1

**

This article reproduces: https://www.cnblogs.com/OnlyCT/p/7845660.html#t1

Catalog

@Cacheable

@ Cacheable is used to declare that methods are cacheable. Store the results in the cache so that the actual method is not required for subsequent calls using the same parameters. Get values directly from the cache. The simplest format requires a cache name.
For example:

@Cacheable("books")
public Book findBook(ISBN isbn) {...}

In the code snippet above, the findBook method is associated with a cache called books. Each time this method is invoked, the request is checked in the cache to avoid repeated execution. Although in most cases only one cache is declared, annotations allow you to specify multiple names to use multiple caches. In this case, before executing the method, each cache checks the method that was executed before, and returns the relevant value directly from the cache as long as there is a cache hit.
All other caches that do not contain this value will be updated even if no caching method is actually executed.
For example:

@Cacheable({"books", "isbns"})
public Book findBook(ISBN isbn) {...}

Default key generation:
The default key is generated according to the following rules:

  • If there are no parameters, use 0 as key
  • If there is only one parameter, use that parameter as key
  • If you have more than one parameter, use hashCode with all the parameters as the key

Custom key generation:
When there are multiple target method parameters, some parameters are not suitable for caching logic
For example:

@Cacheable("books")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

In this case, Cacheable allows you to specify key attributes that generate keys and supports SpringEL expressions. (Recommendation method)
Look at some more examples:

@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

@Cacheable(cacheNames="books", key="#isbn.rawNumber")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

@Cacheable(cacheNames="books", key="T(someType).hash(#isbn)")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

@Cacheable(cacheNames="books", key="#map['bookid'].toString()")
public Book findBook(Map<String, Object> map)

Cached synchronous sync:
In a multithreaded environment, some operations may be invoked synchronously with the same parameters. By default, the cache does not lock any resources, which may result in multiple computations and violate the purpose of the cache. For these specific cases, the attribute sync can indicate that the underlying layer locks the cache so that only one thread can enter the calculation, while other threads block until the return result is updated to the cache.
Example:

@Cacheable(cacheNames="foos", sync="true")
public Foo executeExpensiveOperation(String id) {...}

Attribute condition:
Sometimes, a method may not be suitable for caching all the time (for example, it may depend on a given parameter). Attribute condition supports this function by specifying a boolean value that can be evaluated through a SpEL expression, which is cached for true (evaluated before the method is executed).
Example:

@Cacheable(cacheNames="book", condition="#name.length < 32")
public Book findBook(String name)

In addition, there is an unless attribute that can be used to determine whether to add to the cache. Unlike condition, unless expressions are evaluated after method calls. If false is returned, the cache is placed (as opposed to condition). # result refers to the return value example:

@Cacheable(cacheNames="book", condition="#name.length < 32", unless="#result.name.length > 5"")
public Book findBook(String name)

@CachePut

If the cache needs to be updated and does not interfere with the execution of the method, you can use the annotation @CachePut. @ The CachePut annotation method does not check the existence of previously executed results in the cache before execution. Instead, it executes the method every time and stores the execution results in the specified cache in the form of key-value pairs.

@CachePut(cacheNames="book", key="#isbn")
public Book updateBook(ISBN isbn, BookDescriptor descriptor)

Note: Use of @CachePut and @Cacheable should be avoided.

@CacheEvict

spring cache not only supports data caching, but also supports deleting cached data. This process is often used to remove expired or unused data from the cache.
@ CacheEvict requires that one or more caches be specified to be affected. In addition, an additional parameter, allEntries, is provided. Indicates whether all elements in the cache need to be cleared. The default is false, which means no need. When all Entries are specified as true, Spring Cache ignores the specified key. Sometimes we need Cache to clear all the elements.

@CacheEvict(cacheNames="books", allEntries=true)
public void loadBooks(InputStream batch)

Clearance is triggered by default after the corresponding method has been successfully executed, that is, if the method fails to return successfully because of an exception thrown, it will not trigger Clearance. Using beforeInvocation can change the time when the trigger clearance operation is triggered, and when we specify that the attribute value is true, Spring clears the specified element in the cache before calling the method.

@CacheEvict(cacheNames="books", beforeInvocation=true)
public void loadBooks(InputStream batch)

@CacheConfig
Sometimes there may be multiple caching operations in a class, and these caching operations may be repetitive. You can use @CacheConfig at this time

@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {

@Cacheable
public Book findBook(ISBN isbn) {...}

}

@CacheConfig

It is a class-level annotation that allows shared cache names, KeyGenerator, CacheManager, and CacheResolver.
This operation will be overwritten.

Open Cache Annotations
java class configuration:

@Configuration
@EnableCaching
public class AppConfig {
}

XML configuration:

Copy code

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <cache:annotation-driven />

  </beans>

Tags: Attribute Spring Java xml

Posted on Tue, 06 Aug 2019 03:24:18 -0700 by drtanz