web123456

Using Spring Cache with 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.2 Configuration files

  1. #Names can be automatically configured
  2. #-names=qq
  3. =redis
  4. #Set data survival time1hourly
  5. -to-live=3600000
  6. #key prefix
  7. -prefix=CACHE_
  8. #Whether or not the key is prefixed
  9. -key-prefix=false
  10. # Whether to cache null values to prevent cache penetration
  11. -null-values=true

2.3 Configure RedisCacheConfiguration yourself (if not you need to put @EnableCaching on the startup class)

  1. package ;
  2. import ;
  3. import ;
  4. import ;
  5. import ;
  6. import ;
  7. import ;
  8. import ;
  9. import ;
  10. import ;
  11. @EnableConfigurationProperties()
  12. @Configuration
  13. @EnableCaching
  14. public class MyCacheConfig {
  15. @Bean
  16. RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
  17. RedisCacheConfiguration config = ();
  18. //Set the key to be saved in string type and the value to be saved in json format.
  19. config = ((new StringRedisSerializer()));
  20. config = ((new GenericFastJsonRedisSerializer()));
  21. CacheProperties.Redis redisProperties = ();
  22. //Enable all configurations in the configuration file
  23. if (() != null) {
  24. config = (());
  25. }
  26. if (() != null) {
  27. config = (());
  28. }
  29. if (!()) {
  30. config = ();
  31. }
  32. if (!()) {
  33. config = ();
  34. }
  35. return config;
  36. }
  37. }

2.4 Operating with Annotations

  1. /**
  2. * :: Each piece of data to be cached specifies the name of the cache to which it is to be placed. [Partitioning of caches (by business type)]
  3. * Represents that the result of the current method needs to be cached; if it is in the cache, the method will not be called, if it is not in the cache, the method will be called. and puts the result of the method into the cache
  4. * :: Default behavior
  5. * :: 1) Methods are no longer called if they are in the cache
  6. * :: 2) key is generated by default: cached name::SimpleKey::[] (auto-generated key value)
  7. * :: 3) cached value value, the default use of jdk serialization mechanism, the serialized data will be stored in redis
  8. * 4) The default ttl time is -1:
  9. *
  10. * :: User-independent operations: key generation
  11. * :: 1) Specify the key for generating the cache: the key attribute can be specified to receive a Spel
  12. * :: 2) Specify the survival time of cached data: modify the survival time in the configuration file
  13. * :: 3) Save data in json format
  14. * CacheAutoConfiguration->RedisCacheConfiguration->Automatically configures the RedisCacheManager->Initializes all caches.
  15. * - "Each cache decides what configuration to use - &> if the redisCacheConfiguration is available, use the existing one, if not, use the default one - &> to change the cache configuration, just give the container the
  16. * Just put a RedisCacheConfiguration in -> and it will be applied to all cache partitions managed by the current RedisCacheManager.
  17. *
  18. */
  19. @Cacheable(value={"category"},key="#",sync = true)
  20. @Override
  21. public List<CategoryEntity> getLevel1Categorys() {
  22. return this.(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
  23. }

2.5 Accessing the redis database

2.6 Add two more methods

  1. @Cacheable(value = "category",key="#")
  2. @Override
  3. public Map<String, List<Catelog2Vo>> getCatelogJson() {
  4. //Business Operations.
  5. }
  1. // Use @Caching for multiple operations
  2. @Caching(evict = {
  3. @CacheEvict(value = "category",key="'getLevelCategorys'"),
  4. @CacheEvict(value = "category",key="'getCatelogJson'")
  5. })
  6. @Transactional
  7. @Override
  8. public void updateCascade(CategoryEntity category) {
  9. this.updateById(category);
  10. (());
  11. (());
  12. ((),());
  13. }

2.7 Running the test

First, execute the getLevel1Categorys() and getCatelogJson() methods, you can see thatredisThe database holds their cached data.

Then the updateCascade() method is run, and the data disappears. @Caching can do multiple operations at once, and @CacheEvict can delete the specified cache.

Supplementary: will

@Caching(evict = {
        @CacheEvict(value = "category",key="'getLevelCategorys'"),
        @CacheEvict(value = "category",key="'getCatelogJson'")
})

replace with

@CacheEvict(value = "category",allEntries = true) //Delete all data under a partition

The same effect can be obtained.

Also, replace the configuration file with:

  1. #Names can be automatically configured
  2. #-names=qq
  3. =redis
  4. #Set data survival time1hourly
  5. -to-live=3600000
  6. #key prefix
  7. #-prefix=CACHE_
  8. #Whether or not the key is prefixed
  9. -key-prefix=true
  10. # Whether to cache null values to prevent cache penetration
  11. -null-values=true

Execute the execution of getLevel1Categorys() and getCatelogJson() two methods, you can see two cached data in the database categorized under category:

3, SpringCache shortcomings

1), read mode
Cache Penetration: query a null data. Solution: Cache null data.

-null-values=true

Cache hit: a large number of concurrent incoming queries for a data that happens to be out of date at the same time. Solution: add locks ? No locking by default; use sync = true to solve the breakdown problem.

@Cacheable(value={"category"},key="#",sync = true)

Cache avalanche: a large number of keys expired at the same time. Solution: add random time. Add expiration time.

-to-live=3600000

2), Write mode: (caching is consistent with the database)
Read and write locking.
pull intoCanal, Sensing MySQL updates to update Redis
Read more, write more. Just go straight to the database.

4. Summary

Regular data (read more write less, immediacy, consistency requirements are not high data, completely can use Spring-Cache): write mode (as long as the cached data has an expiration time is enough)

Principle: CacheManager (RedisCacheManager) - & gt; Cache (RedisCache) - & gt; Cache is responsible for the cache read and write