SpringBoot special study Part25: Spring Cache Cache abstract use (@ Cacheable, @ CachePut, @ CacheEvict, @ Caching, @ CacheConfig)

First, the concept

Cache is a function of each system should be considered for performance and enhance the system to accelerate access system

For example, a Web site electricity supplier product information every time if time-consuming database query is too large
then you can introduce a cache middleware product data information into the cache would not directly query the database query cache to
cache if the If the cache is not directly query the database and data information into the cache
case because the application and cache interaction is very fast speed much faster than the query database, especially the huge database

Or the processing temporary data such as three minutes effectively run codes is deleted
then the data may be placed in the cache system can be accessed from the cache when the cache is deleted from the time
application scenario is widely used

1, JSR 107

In order to develop a unified cache standardize and improve system scalability
J2EE released the JSR-107 specification cache

Java Caching defines five core interfaces are CachingProvider and CacheManager and Cache and Entry and Expiry
of which:

  • CachingProvider (cache provider) definition creates a configuration obtaining management and control of multiple CacheManager (Cache Manager)
    An application can access multiple CachingProvider at runtime

  • CacheManager (Cache Manager) to create and control the configuration definition management acquire a plurality of uniquely named Cache
    These Cache CacheManager present in the context of
    a CacheManager only be owned by a CachingProvider

  • Cache (Cache) is a similar Map data structure and temporarily stored in a Key Index value of
    a Cache can only be owned by a CacheManager

  • Entry is stored in the Cache key key-value pair

  • Expiry is valid for
    each entry stored in the Cache there once a defined time period exceeding this entry shall expire status
    Once expired, the entry will be inaccessible to update and delete
    the cache is valid by setting ExpiryPolicy

Here Insert Picture Description
JSR-107 are defined by a number of interfaces such similar programming interfaces directly to JDBC
natural goose market but not all components of the buffer provides an implementation of the JSR-107
similar implementations absence shall be implemented to write their respective
Thus JSR not a lot of use -107

2, SpringCache cache abstraction

Spring After the introduction of 3.1 based caching annotation is not the nature of a particular implementation, but a buffer cache use abstract
by adding both the code which is defined in the annotation i.e. buffer effect can be achieved

Defines org.springframework.cache.Cacheand org.springframework.cache.CacheManagertwo interfaces to unify different caching techniques
and supports JCache (JSR-107) annotations to simplify the development
Here Insert Picture Description

①, class

  • Cache : Cache interface defines the cache operation
    it has achieved RedisCache EhCacheCache ConcurrentMapCache other
    cache Cache interface technology is used in various different
  • The CacheManager : Cache Manager to manage the various components of the cache (Cache)

②, notes

  • @Cacheable: Add the annotation method depending on the request can be cached results of its process
    result is marked the annotation will be cached
    Example:
@Cacheable
public User getUser(Integer id)
  • @CacheEvict: Clear Cache
    cases:
@CacheEvict
public void deleteUser(Integer id)
  • @CachePut: Method is called and want to ensure that the results are cached
    for cache updates
    example:
@CachePut
publit User updateUser(User user)
  • @EnableCaching: Label annotation-based caching is turned on startup class

Second, the use

When you create a project using the Wizard to the introduction of Spring Cache module
Here Insert Picture Description
or add their own dependence:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Then on the main class plus @EnableCachingcomment open annotation-based caching :

Note: You must open or can not use the cache
@MapperScan("net.zjitc.springboot.mapper")
@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCacheApplication.class, args);
    }
}

After the cache is to add the appropriate annotation on the method:
In the case of course, I use the MyBatis persistence framework can also be other

1 @CacheableNote:

Use @Cacheableannotation will run cache results of the method
can be obtained directly from the cache after a while and then need to get the same data

@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Cacheable(cacheNames = "emp",key = "#id")
    public Employee findEmployee(Integer id)
    {
        return employeeMapper.findEmployeeById(id);
    }
}

@Cacheable properties of the annotation:

  • cacheName or value : Specifies the name of the cache
    CacheManager cache manager can manage a plurality of cache component
    real operations in the buffer cache is a cache component for each component has its own unique name
    available to specify an array of a plurality of names separated by commas
  • key : key to be used when the data cache
    data is key-key-value pairs for storing
    a default value, for example, use the input parameters to return a key to a value that User1 User1 is
    available spEL expression
    # a0 = # p0 = # root.args [0]
    can be spliced Example: "# root.methodName + '[' + # id + ']'"
  • keyGenerator : specified key generator default cache key as a parameter value may be self-generated by the generator
    both the key and can only choose one keyGenerator
  • CacheManager : specifies the Cache Manager
  • cacheResolver : Specifies the parser cache
    cacheResolver obtained is cached is set to give a single cache cacheManager
    cacheResolver cacheManager and a second election
  • for condition Condition : Specifies the case before qualifying cache
  • The unless : not cached that match the conditions of the case
    and the opposite condition
    Example: unless = # result == null null result is not cached
  • Sync : whether to use asynchronous mode cache

spEL expression:
Here Insert Picture Description
the flow of execution :
in @Cacheablebefore the method of execution marked notes first check whether there is a default in accordance with the data values of the parameters as key to cache query cache
method is invoked if there is no value to query the database and the results are placed in the cache
if get the value of the data returned directly method does not call to query the database

Core :
Use CacheManager name obtained according to the Cache components
CacheManager by default, it ConcurrentMapCacheManager
Cache by default, it ConcurrentMapCache

Use key keyGenerator to generate a
default, it SimpleKeyGenerator


keyGeneratorProperty specifies the key generator

Write a configuration class to configure:

@Configuration
public class MyCacheConfig {

    @Bean("myKeyGenerator")
    public KeyGenerator keyGenerator()
    {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                return method.getName()+"["+ Arrays.asList(params).toString()+"]";
            }
        };
    }
}

Then fill in the name of the builder of the property where you can keyGenerator

@Cacheable(cacheNames = "emp",keyGenerator = "myKeyGenerator")
public Employee findEmployee(Integer id)
{
    System.out.println("查询"+id+"号员工");
    return employeeMapper.findEmployeeById(id);
}

conditionCache property specifies conditions
@Cacheable(cacheNames = "emp",keyGenerator = "myKeyGenerator",condition = "#a0==2")
public Employee findEmployee(Integer id)
{
    System.out.println("查询"+id+"号员工");
    return employeeMapper.findEmployeeById(id);
}

condition = "#a0==2"Means: when the cache if the first parameter is 2
, and add additional conditions and the like are connected, for example, to achieve multiple determination and eq


unlessDo not cache attribute specifies the conditions
@Cacheable(cacheNames = "emp",keyGenerator = "myKeyGenerator",unless = "#a0==2")
public Employee findEmployee(Integer id)
{
    System.out.println("查询"+id+"号员工");
    return employeeMapper.findEmployeeById(id);
}

unless = "#a0==2"Means: when the first parameter is not cached only 2
for condition Condition and can exist unless


2, @CachePutnotes:

Calling both methods and update data
typically used for updating method of modifying data

@CachePut(cacheNames = "emp")
public Employee updateEmployee(Employee employee)
{
    employeeMapper.updateEmployee(employee);
    return employee;
}

@CachePut execution timing and @Cacheable different
@Cacheableare judged before the method invocation
and @CachePutis the first result of the method invocation method then placed in the cache
anyway method will be executed to

There is a point to note:
the default key value is the key parameter default is therefore @CachePut incoming objects
and @Cacheable is the default key is passed in the query parameters
so that they are two data will be stored in the cache update after the data does not overwrite the data in the cache is
therefore to be covered with a uniform specified key corresponds to the house number is the same as before to obtain another recognition

@CachePut(cacheNames = "emp",key = "#employee.id")
public Employee updateEmployee(Employee employee)
{
    System.out.println("更新了 最新数据:"+employee);
    employeeMapper.updateEmployee(employee);
    return employee;
}

or

@CachePut(cacheNames = "emp",key = "#result.id")
public Employee updateEmployee(Employee employee)
{
    System.out.println("更新了 最新数据:"+employee);
    employeeMapper.updateEmployee(employee);
    return employee;
}

Both versions are # employee.id be taken from the reference attribute value rather ** # result.id ** attribute value is taken from the results
the results for the update operation for updating attribute values and the reference attribute value is and the same @CachePutmethod of labeling must be executed and therefore must be a result of the results
and @Cacheable not possible to value the results because @Cacheablethe method of labeling would not necessarily be executed thus will not necessarily result


3, @CacheEvictnotes

The annotation is used to clear the cache
to specify the key attribute to be cleared by Cache
If the default settings key parameter values passed

@CacheEvict(cacheNames = "emp",key = "#id")
public void deleteEmployee(Integer id)
{
    System.out.println("删除了"+id);
    employeeMapper.deleteEmployee(id);
}
allEntriesProperty is delete all the data specified cache
@CacheEvict(cacheNames = "emp",allEntries = true)
public Integer deleteEmployee(Integer id)
{
    System.out.println("删除了"+id);
    employeeMapper.deleteEmployee(id);
    return id;
}

beforeInvocationBefore clearing the data in the cache is in the process of implementation of property

The default is false that is cleared after execution method
difference is clear after the method execution if an error if the cache is not cleared during the execution method
and the method regardless of whether an error occurred clearing the cache will be cleared before execution method

@CacheEvict(cacheNames = "emp",allEntries = true,beforeInvocation = true)
public Integer deleteEmployee(Integer id)
{
    System.out.println("删除了"+id);
    employeeMapper.deleteEmployee(id);
    return id;
}

4, @Cachingcomment

@Caching Annotations are @Cacheablenotes and @CachePutannotations and @CacheEvictcomprehensive annotated version of
a three-annotation is used to define complex rules cache
inside is this:

public @interface Caching {

	Cacheable[] cacheable() default {};

	CachePut[] put() default {};

	CacheEvict[] evict() default {};

}

When the cache rules are complex when the annotation can be used to specify multiple rules

@Caching(cacheable = {@Cacheable(cacheNames="emp",key="#lastName")},
        put = {@CachePut(cacheNames="emp",key="#result.id"),
                @CachePut(cacheNames="emp",key="#result.email")})
public Employee getEmployeeByLastName(String lastName)
{
    return employeeMapper.getEmployeeByLastName(lastName);
}

5 @CacheConfigcomment

The add annotation specifies the class in the class cache configuration common property
inside is such that:

public @interface CacheConfig {

	String[] cacheNames() default {};

	String keyGenerator() default "";

	String cacheManager() default "";

	String cacheResolver() default "";

}

After you specify the class attribute inside the corresponding cache all annotations are not configured:

@Service
@CacheConfig(cacheNames = "emp")
public class EmployeeService {

    @Caching(cacheable = {@Cacheable(key="#lastName")},
                put = {@CachePut(key="#result.id"),
                        @CachePut(key="#result.email")})
        public Employee getEmployeeByLastName(String lastName)
        {
            return employeeMapper.getEmployeeByLastName(lastName);
        }
}

Published 174 original articles · won praise 5 · Views 240,000 +

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105160437