The core
- Cache interface, provides the Cache operation API
- CacheManager manages caches
Conditions of use
Rely on
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
Copy the code
The configuration file
Spring: cache: # Specifies the cache typeCopy the code
Start class annotations
@EnableCaching
Copy the code
Cache usage
annotationsCacheable
:
- Classes can be annotated as well as methods
- Caches the return result of an annotation object, caches the return value of that method on a method, and caches the return value of all methods in that class on a class
- Value There can be multiple cache names
- Key cache key rules, which can be springEL expressions, default to method parameter combinations
- Condition The cache condition, written in springEL, returns true
@cacheable (value = {"redis cache name "},key = "#root.methodName") //root.methodName Public ProductDO findById(int id) public ProductDO findById(int id)Copy the code
CacheManager using
- Set Redis expiration time and serialization
Public RedisCacheManager cacheManager1Day(RedisConnectionFactory connectionFactory) { RedisCacheConfiguration config = instanceConfig(3600 * 24L); return RedisCacheManager.builder(connectionFactory). cacheDefaults(config). transactionAware(). build(); } private RedisCacheConfiguration instanceConfig(Long ttl) { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.registerModule(new JavaTimeModule()); Objectmapper. configure(mapperfeature. USE_ANNOTATIONS, false); / / only for non-null value serialize objectMapper. SetSerializationInclusion (JsonInclude. Include. NON_NULL); / / the type of serialization to attribute the json string objectMapper. ActivateDefaultTyping (LaissezFaireSubTypeValidator instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); return RedisCacheConfiguration.defaultCacheConfig(). entryTtl(Duration.ofSeconds(ttl)). disableCachingNullValues(). serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)); }Copy the code
The custom key: KeyGenerator
@Bean public KeyGenerator springCacheCustomKeyGenerator(){ return new KeyGenerator() { @Override public Object generate(Object o, Method method, Object... Objects) {// custom naming methods}}}Copy the code
- Use CacheManager and KeyGenerator
@Cacheable(value = {"product"},keyGenerator = "springCacheCustomKeyGenerator",cacheManager = "cacheManager1Min")
CachePut
- Update redis cache data in real time when database update data, each request will be triggered
- Value The cache name can be multiple
- Key can be SpringEL expressions, not KeyGenerator
- Condition The cache condition, written in SpringEL, returns true
@cacheput (value = {"product"},key = "# productdo. id",cacheManager = "cacheManager1Min")Copy the code
CacheEvict
- Used to remove data from the cache
- When database data is deleted, the data cached in Redis is also deleted
- Key can be SpringEL expressions, not KeyGenerator
- beforeInvocation = false
- Whether to clear the cache before the method is executed, the default is after the method
- If an exception occurs, the cache is not cleared
- beforeInvocation = true
- Means that the cache is cleared before the method is executed, regardless of the exception
@CacheEvict(value = {"product"},beforeInvocation = false)
Copy the code
Caching
- Multiple Cacheable, CachePut, and CacheEvict annotations can be nested in the Caching annotation
@caching (cacheable = {@cacheable (value = {}...)) @caching (cacheable = {@cacheable (value = {}...) , @Cacheable(value = ...) }, put = { @CachePut(...) })Copy the code
Sync attribute
- SpringCache’s sync property, true, opens the lock, requesting a one-by-one resolution, which can be used for cache breakdowns
@Cacheable(value = {"product"},key = "xxx",sync = true)