web123456

SpringCache Use of Redis as a Caching Technology

present (sb for a job etc)

Spring Cache is a framework that implements an annotation-based caching functionality , just simply add an annotation , you can achieve caching functionality , greatly simplifying our business in the operation of the cache code .

Spring Cache just provides a layer of abstraction, the bottom can switch between different cache implementations. Specifically through the CacheManager interface to unify the different caching technologies . CacheManager is Spring provides a variety of caching technology abstraction interface.

Different CacheManagers need to be implemented for different caching technologies:

CacheManager

descriptive

EhCacheCacheManager

Using EhCache as a caching technique

GuavaCacheManager

Using Google's GuavaCache as a caching technique

RedisCacheManager

utilizationRedisAs a caching technique

explanatory note

existSpringCacheThere are a number of annotations provided for caching operations, the common ones being the following:

annotate

clarification

@EnableCaching

Enable caching annotations , add the

@Cacheable

Before the method is executed spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value into the cache

@CachePut

Putting the return value of a method into the cache

@CacheEvict

Remove one or more pieces of data from the cache

In a spring boot project, all you need to do to use caching is to import the relevant caching dependency packages in the project and turn on caching support using @EnableCaching on the startup class.

For example, to use Redis as a caching technology, simply import the Spring data RedismavenCoordinates are sufficient.

Use SpringCach main attention to the design of the key, because the cache data, you may want to cache a number of copies of these data can not be mixed up, it is necessary to distinguish according to the key, and the key is often dynamic, for example, I dynamically use the current user's id as the key, how to get the id, it provides us with a kind ofSPEL expressionlanguage, in this way it is possible to dynamically obtain the user's di

For example, the key to get the id of an object is written as follows: both can be used, and it is recommended to use them because the id is unique.

# : #user refers to the name of the method's formal parameter, id refers to the user's id attribute, i.e., the user's id attribute is used as the key.

#: #user refers to the name of the method's formal parameter, name refers to the name attribute of the user, i.e., the name attribute of the user is used as the key.

# : #result represents the return value of the method, and this expression represents the id attribute of the returned object as the key;

# : #result represents the return value of the method, and this expression represents the name attribute of the returned object as the key;

To use redis for caching, you need to do the following steps:

Steps to use Spring Cache in a Spring Boot project (using redis caching technology)

1. Importing maven coordinates.spring-boot-starter-cache , spring-boot-starter-data-redis

2. Configuration Setting the cache validity period

3. Write Redis configuration class RedisConfig, define RedisTemplate.

4. Add the @EnableCaching annotation to the startup class to enable the caching annotation.

5. Add @Cacheable . @CacheEvict , @CachePut , etc. , for caching operations.

1). Import 2 maven coordinates spring-boot-starter-cache , spring-boot-starter-data-redis

  1. <dependency>
  2. <groupId></groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId></groupId>
  7. <artifactId>spring-boot-starter-data-redis</artifactId>
  8. </dependency>

2). Configuration Add redis related configuration , set cache validity period

  1. spring:
  2. redis:
  3. host: 172.0.0.1
  4. port: 6379
  5. password: 123456 # Own password
  6. database: 0
  7. cache:
  8. redis:
  9. time-to-live: 1800000 # Setting the cache expiration time30Minutes, optional

3). Write the Redis configuration class RedisConfig, define the RedisTemplate

Framework default declaration of the RedisTemplate with the key and value serialization is the default JdkSerializationRedisSerializer, if the key is serialized in this way, we end up in the test through the redis graphical interface query is not very convenient, so use our customized RedisTemplate, the key is serialized using the StringRedisSerializer, that is, string form

  1. import .CachingConfigurerSupport;
  2. import .Bean;
  3. import .Configuration;
  4. import .RedisConnectionFactory;
  5. import .RedisTemplate;
  6. import .StringRedisSerializer;
  7. @Configuration
  8. public class RedisConfig extends CachingConfigurerSupport {
  9. @Bean
  10. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
  11. RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
  12. // The default Key serializer is: JdkSerializationRedisSerializer
  13. (new StringRedisSerializer());
  14. (connectionFactory);
  15. return redisTemplate;
  16. }
  17. }

4). Add the @EnableCaching annotation to the startup class to enable the caching annotation.

5). Add @Cacheable . @CacheEvict , @CachePut , etc. , to perform caching operations.

1. @Cacheble a Note Description.

Role: Before the method is executed, spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value to the cache

value: the name of the cache, there can be more than one key under each cache name

key: cached key ----------> support Spring's Expression Language SPEL syntax

condition : Indicates what conditions are met before caching.

unless : does not cache if the condition is met; the reverse of condition above.

  1. /**
  2. * :: Cacheable: before the method is executed spring first check whether there is data in the cache, if there is data, then directly return the cached data; if there is no data, call the method and put the method return value into cache
  3. * :: value: the name of the cache, there can be more than one key under each cache name
  4. * :: key: cached key
  5. * condition: conditions, meet the conditions before caching the data , can not use the result inside is no result object.
  6. * :: unless: no caching if conditions are met
  7. */
  8. @Cacheable(value = "userCache",key = "#id", unless = "#result == null")
  9. @GetMapping("/{id}")
  10. public User getById(@PathVariable Long id){
  11. User user = (id);
  12. return user;
  13. }

Annotate the list method with @Cacheable

When querying in the list method, there are two query conditions, if you pass the id, according to the id query; if you pass the name, according to the name query, then we cache the key in the design, we need to include both id and name.

  1. @Cacheable(value = "userCache",key = "# + '_' + #")
  2. @GetMapping("/list")
  3. public List<User> list(User user){
  4. LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
  5. (() != null,User::getId,());
  6. (() != null,User::getName,());
  7. List<User> list = (queryWrapper);
  8. return list;
  9. }

2. @CacheEvict annotation:

Function: Clears the specified cache

value: the name of the cache, there can be more than one key under each cache name

key: cached key ----------> supports Spring's Expression Language SPEL syntax , can dynamically calculate the value of the key

1). Add the @CacheEvict annotation to the delete method When we delete data from the user table in the database, we need to delete the corresponding data in the cache, and then we can use the @CacheEvict annotation, which is used as follows.

  1. * CacheEvict: Clears the specified cache.
  2. * value: the name of the cache, there can be more than one under each cache namekey
  3. * keycachedkey
  4. */
  5. //@CacheEvict(value = "userCache",key = "#p0") //#p0 Represents the first parameter
  6. //@CacheEvict(value = "userCache",key = "#[0]") //#[0] represents the first parameter
  7. @CacheEvict(value = "userCache",key = "#id") //#id Represents a parameter with variable name id Recommended Use
  8. @DeleteMapping("/{id}")
  9. public void delete(@PathVariable Long id){
  10. (id);
  11. }

2). Add the annotation @CacheEvict to the update method After updating the data, the data in the database has changed, and we need to remove the corresponding data from the cache to avoid inconsistencies between the database data and the cached data.

  1. //@CacheEvict(value = "userCache",key = "#") //The id attribute of the first parameter
  2. //@CacheEvict(value = "userCache",key = "#[0].id") //The id attribute of the first parameter
  3. //@CacheEvict(value = "userCache",key = "#") //The id attribute of the return value
  4. @CacheEvict(value = "userCache",key = "#") //The id attribute of the parameter named user parameter
  5. @PutMapping
  6. public User update(User user){
  7. (user);
  8. return user;
  9. }

3) Add new package Clear cache for deleted packages allEntries = true

  1. /**
  2. * :: Deletion of packages
  3. * @param ids
  4. * @return
  5. */
  6. @DeleteMapping
  7. @CacheEvict(value = "setmealCache",allEntries = true) //Clear all cached data under the name setmealCache.
  8. public R<String> delete(@RequestParam List<Long> ids){
  9. ("ids:{}",ids);
  10. (ids);
  11. return ("Package data deleted successfully.");
  12. }
  13. **
  14. * :: New packages added
  15. * @param setmealDto
  16. * @return
  17. */
  18. @PostMapping
  19. @CacheEvict(value = "setmealCache",allEntries = true) //Clear all cached data under the name setmealCache.
  20. public R<String> save(@RequestBody SetmealDto setmealDto){
  21. ("Package information: {}",setmealDto);
  22. (setmealDto);
  23. return ("New package added successfully");
  24. }

3 . @CachePut annotation description:

What it does: puts the return value of the method into the cache.

value: the name of the cache, each cache name can have many keys under it

key: cached key ----------> support Spring's Expression Language SPEL syntax

1). Annotate the save method with @CachePut

The save method is used to save the user's information. If we want to cache a copy of the user's information while it is being saved to the database, we can add the @CachePut annotation to the save method.

  1. /**
  2. * CachePut: puts method return values into the cache The underlying cache used now is Map
  3. * value: the name of the cache, there can be more than one under each cache namekey
  4. * keycachedkey
  5. */
  6. @CachePut(value = "userCache", key = "#")
  7. @PostMapping
  8. public User save(User user){
  9. (user);
  10. return user;
  11. }