Personal blog address :http://alexaccele.github.io/
1. Import cache modular
To be in springboot In order to use caching technology in Import springboot The cache module of , stay pom Add the following code to the file , Or select… When creating the project cache modular , The two are the same , Choose cache The module will also be in pom Add the following code to the file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2.@EnableCaching Turn on annotation-based caching
Add… To the configuration class @EnableCaching annotation , It can also be marked on the main function entry of the program
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class SpringbootConfiger {
}
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
Application.run(Application.class, args);
}
}
3. Mark cache annotations on methods
Four annotations to declare caching rules
annotation | describe |
@Cacheable | Indicates that before calling a method , First you should look up the return value of the method in the cache . If this value can be found , It will return the cached value . Otherwise , This method will be called , The return value is put in the cache |
@CachePut | Indicates that the return value of the method should be put in the cache , The cache is not checked before the method is called , Method always calls |
@CacheEvict | Indicate that Clear one or more entries in the cache , Usually used to delete database data , Delete the contents of the cache according to the input parameters . |
@Caching | This is a group note , can Apply multiple other cache annotations at the same time |
Examples are as follows :
/* This method will look for... In the cache first key by id The data of , If it exists, the query statement will not be sent to get the object directly , Otherwise, execute the method to query and return User Objects are put into the cache */
@Cacheable
public User findOne(Long id){
return repository.findOne(id);
}
/* Whether or not there is in the cache key by id Of User object , Methods are executed and stored in the cache */
@CachePut
public User findOne(Long id){
return repository.findOne(id);
}
/* Not only will the database be deleted id by User The data of , It also clears the cache id by User The data of */
@CacheEvict
public User remove(Long id){
return repository.remove(id);
}
/*@Cacheable and @CachePut The combination of annotations */
@Caching(
cacheable = {@Cacheable(value="user",key="#id")},
put = {@CachePut(value="user",key="#result.name")}
)
public User findOne(Long id){
return repository.findOne(id);
}