Integrate Spring Cache

  Next, use the caching technology provided by Spring to implement the use of Redis cache. Before using it, you need to understand the two modes of caching: read mode and write mode . The
  read mode is how to read a data, which needs to be read from the cache. If there is no query in the database in the cache, the data is found in the cache for the next use; the
  write mode is to store the data in the cache, but the write mode needs to maintain the consistency of the cache and the database data, you can use double write mode or failure mode
  dual-write mode is that when we modify certain data in the database will be updated modified data to the cache, the old data is overwritten
  failure modes of the same when a modified data, we just Clear all the caches where the current data is located, and go directly to the database to query the latest data
  in the next query. Of course, in the previous use, these codes are duplicated, so Spring specially extracted an abstraction layer for the cache: Spring cache; Spring version 3.1 defines the org springframework.cache.Cache and org springframework.cache.CacheManager interfaces to unify the different cache technology, and support JCache annotations to simplify the development, operations, refer to the official documentation (.. portal )
  Next Start using Sring Cache

  1. Import the jar package, pay attention to which one needs to be used as a cache to import it, for example, I use redis as an example

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

  2. Write the configuration, because I am using Redis cache, I need to configure Redis related first

spring:
  redis:
    host: 192.168.0.109
  cache:
    type: redis # 指定缓存的类型
    redis:
      time-to-live: 3600000 # 过期时间,单位毫秒
      key-prefix: cache_ # key的前缀
      use-key-prefix: true # 是否使用前缀
      cache-null-values: true # 是否缓存空值,防止缓存穿透

  3. First understand the annotations of Harbin Cache

  • @Cacheable : Trigger the operation of saving data to the cache
  • @CacheEvict : Trigger the operation to delete data from the cache
  • @CachePut : Update the cache without affecting the execution of the method
  • @Caching : Combine multiple cache operations
  • @CacheConfig : share the same configuration of the cache at the class level

  4. Customize the cache configuration class and enable caching through the @EnableCaching annotation

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableCaching // 开启缓存
@Configuration
@EnableConfigurationProperties(CacheProperties.class)//绑定属性配置
public class MyCacheConfig {
    
    

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
    
    
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //key的序列化方式
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //value的序列化方式
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        //过期时间
        if (redisProperties.getTimeToLive() != null) {
    
    
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        //key前缀
        if (redisProperties.getKeyPrefix() != null) {
    
    
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        //是否缓存空值
        if (!redisProperties.isCacheNullValues()) {
    
    
            config = config.disableCachingNullValues();
        }
        //是否使用前缀
        if (!redisProperties.isUseKeyPrefix()) {
    
    
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

  5. Start the test. In the test, the first time there is no data in the cache, the query database is executed, and the second time there is data in the cache, the data in the cache is directly returned without executing the query database

@Override
@Cacheable(value = RedisKeyUtils.catalogKey)//指定key
public List<CategoryEntity> getCatalogJsonWithRedisson() {
    
    
    List<CategoryEntity> categoryEntities = listWithTree();
    return categoryEntities;
}

Guess you like

Origin blog.csdn.net/weixin_45481406/article/details/113484554