Spring 3.1 introduces an annotation (annotation)-based cache technology, which is essentially not a specific cache implementation, but rather an abstraction of cache usage by adding a small amount of its defined assists annotation to the existing code. will be able to reach the effect of the cached method's return object.
Characteristics
With considerable flexibility, you can not only use Spel to define cached keys and various condition, but also provide out-of-the-box cache temporary storage schemes, as well as support and mainstream professional caches such as Ehcache, Redis, guava integration.
Based on annotation, allows existing code to support caching
Out-of-the-box out-of-the-box with cache without installing and deploying additional third-party components
Supports spring Express Language, which can use any property or method of an object to define the cached key and condition
Support for ASPECTJ and caching through its implementation of any method
Support for custom key and custom cache managers with considerable flexibility and scalability
Before and after use
Before use:
We need to hard code, if the switch cache client also need to modify the code, high coupling, not easy to maintain
public String get(String key) {
String value = userMapper.selectById(key);
if (value != null) {
cache.put(key,value);
}
return value;
}
After use:
Based on spring cache annotations, the cache is configured by the developer itself, but does not involve a specific encoding
@Cacheable(value = "user", key = "#key")
public String get(String key) {
return userMapper.selectById(key);
}
Add dependency
Need to add Redis dependencies Previous
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
Property configuration
spring:
datasource:
url: jdbc: mysql: // localhost: 3306 / david2018_db? characterEncoding = utf8
username: root
password: 1234
redis:
host: 10.211.55.5 #redis server address
timeout: 10000 #Timeout
database: 0 # 0-15 16 libraries default 0
lettuce:
pool:
max-active: 8 #Maximum number of connections
max-wait: -1 #default -1 maximum connection blocking wait time
max-idle: 8 #Max idle connection default 8
min-idle: 0 #Minimum idle connection
cache:
type: redis
Spring.cache.type is generally self-assembling based on dependent packages, but the sequencing will have an impact on Redis use, (Jcache->ehcache->redis->guava) It is best to manually configure
Entity class
public class t_user implements Serializable {
private Integer id;
private String username;
private String password;
...
}
Mybatisdao
@Mapper
public interface tUserDao {
@Delete("delete from t_user where id = #{id}")
int delete(int id);
@Update("update t_user set username = #{username},password = #{password} where id = #{id}")
int update(t_user user);
@Select("select * from t_user where id = #{id}")
t_user getById(int id);
}
Service
@Service
public class t_userService {
@Resource
private tUserDao dao;
@Cacheable (value = "t_user", key = "# id")
public t_user getById (int id) {
System.out.println ("Enter the query method");
return dao.getById (id);
}
@CacheEvict (value = "t_user", key = "# id")
public int delete (Integer id) {
System.out.println ("Enter the delete method");
return dao.delete (id);
}
@CachePut (value = "t_user", key = "# user.id")
public int update (t_user user) {
System.out.println ("Enter the modification method");
return dao.update (user);
}
}
Controller
@RequestMapping("/t_user")
@RestController
public class t_userController {
@Autowired
private t_userService service;
@GetMapping("/delete")
public String delete(int id){
service.delete(id);
return "delete";
}
@GetMapping("/update")
public String update(t_user user){
service.update(user);
return "update";
}
@GetMapping("/getById")
public String getById(int id){
return service.getById(id).toString();
}
}
Finally, start the cache using @enablecaching in the Startup class
@EnableCaching
@SpringBootApplication
public class BootApplication{
public static void main(String[] args) {
SpringApplication.run(BootApplication.class,args);
}
}
Run test: http://localhost:8088/t_user/getById?id=1 after entering this path, the console only prints once into the Query method description cache, and the modified delete is back to print modified methods and deleted methods, Thus cutting off the data cached in Redis. where # represents a Spel expression.
Manipulating caches based on conditions
The Uancun content does not affect the database operation according to the condition, the conditional expression returns a Boolean value, True/false, when the condition is true, the cache operation, otherwise the direct call method returns the result.
Length: @CachePut (value= "user", key= "#user. Id", condition= "#user. Username.legnth () < 10") cache only data with a user name length less than 10
Size: @Cacheable (value= "user", key= "#id", condition= "#id < 10") cache only data with ID less than 10
Combination: @Cacheable (value= "user", key= "#user. Username.concat (#user. Password)")
Early action: @CacheEvict (value= "user", Allentries=true,beforeinvocation=true) plus beforeinvocation=true, regardless of internal error, the cache will be cleared, The default is False.
Introduction to Annotations
@Cacheable (The result is cached based on the request parameters of the method)
Key: The cached key, can be empty, if specified to be written according to Spel expression, if not specified, then by default all parameters of the method are combined (e.g.: @Cacheable (value= "user", key= "#username"))
Value: The name of the cache, as defined in the spring configuration file, must specify at least one (for example: @Cacheable (value= "user") or @cacheable (value={"user1", "User2"})
Condition: Cached condition, can be empty, written with Spel, returns TRUE or FALSE, only true for caching (such as: @Cacheable (value= "user", key= "#id", condition= "#id < 10 "))
@CachePut (The result is cached based on the request parameters of the method, and unlike @cacheable, it triggers the invocation of the real method each time)
@CacheEvict (empty the cache based on conditions)
Allentries: Clears all cached content, defaults to False, and if true, clears all caches immediately after the method call (for example: @CacheEvict (value= "user", key= "#id", Allentries=true) )
Beforeinvocation: Whether to empty before the method executes, default to False, if true, to empty the cache when the method has not been executed, by default, if the method throws an exception, the cache will not be emptied (for example: @CacheEvict (value= " User ", key=" #id ", Beforeinvocation))
Spring Boot (24) using Spring cache integrated Redis