-
<dependency>
-
<groupId></groupId>
-
<artifactId>spring-boot-starter-cache</artifactId>
-
</dependency>
-
<dependency>
-
<groupId></groupId>
-
<artifactId>spring-boot-starter-data-redis</artifactId>
-
</dependency>
2.2 Configuration files
-
#Names can be automatically configured
-
#-names=qq
-
=redis
-
#Set data survival time1hourly
-
-to-live=3600000
-
#key prefix
-
-prefix=CACHE_
-
#Whether or not the key is prefixed
-
-key-prefix=false
-
# Whether to cache null values to prevent cache penetration
-
-null-values=true
2.3 Configure RedisCacheConfiguration yourself (if not you need to put @EnableCaching on the startup class)
-
package ;
-
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
import ;
-
-
@EnableConfigurationProperties()
-
@Configuration
-
@EnableCaching
-
public class MyCacheConfig {
-
@Bean
-
RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
-
-
RedisCacheConfiguration config = ();
-
//Set the key to be saved in string type and the value to be saved in json format.
-
config = ((new StringRedisSerializer()));
-
config = ((new GenericFastJsonRedisSerializer()));
-
-
CacheProperties.Redis redisProperties = ();
-
//Enable all configurations in the configuration file
-
if (() != null) {
-
config = (());
-
}
-
if (() != null) {
-
config = (());
-
}
-
if (!()) {
-
config = ();
-
}
-
if (!()) {
-
config = ();
-
}
-
-
return config;
-
}
-
}
2.4 Operating with Annotations
-
/**
-
* :: 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)]
-
* 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
-
* :: Default behavior
-
* :: 1) Methods are no longer called if they are in the cache
-
* :: 2) key is generated by default: cached name::SimpleKey::[] (auto-generated key value)
-
* :: 3) cached value value, the default use of jdk serialization mechanism, the serialized data will be stored in redis
-
* 4) The default ttl time is -1:
-
*
-
* :: User-independent operations: key generation
-
* :: 1) Specify the key for generating the cache: the key attribute can be specified to receive a Spel
-
* :: 2) Specify the survival time of cached data: modify the survival time in the configuration file
-
* :: 3) Save data in json format
-
* CacheAutoConfiguration->RedisCacheConfiguration->Automatically configures the RedisCacheManager->Initializes all caches.
-
* - "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
-
* Just put a RedisCacheConfiguration in -> and it will be applied to all cache partitions managed by the current RedisCacheManager.
-
*
-
*/
-
@Cacheable(value={"category"},key="#",sync = true)
-
@Override
-
public List<CategoryEntity> getLevel1Categorys() {
-
return this.(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
-
}
2.5 Accessing the redis database
2.6 Add two more methods
-
@Cacheable(value = "category",key="#")
-
@Override
-
public Map<String, List<Catelog2Vo>> getCatelogJson() {
-
//Business Operations.
-
}
-
// Use @Caching for multiple operations
-
@Caching(evict = {
-
@CacheEvict(value = "category",key="'getLevelCategorys'"),
-
@CacheEvict(value = "category",key="'getCatelogJson'")
-
})
-
@Transactional
-
@Override
-
public void updateCascade(CategoryEntity category) {
-
this.updateById(category);
-
(());
-
(());
-
((),());
-
}
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:
-
#Names can be automatically configured
-
#-names=qq
-
=redis
-
#Set data survival time1hourly
-
-to-live=3600000
-
#key prefix
-
#-prefix=CACHE_
-
#Whether or not the key is prefixed
-
-key-prefix=true
-
# Whether to cache null values to prevent cache penetration
-
-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