导入
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
配置
在配置文件中加入
spring cache type redis # 缓存类型 redis time-to-live 36000000 # 设置过期时间 cache-null-values true # 防止缓存穿透
编写一个配置类,配置序列化规则
CacheProperties.class) (publicclassCacheConfig { publicRedisCacheConfigurationcreateConfiguration(CachePropertiescacheProperties) { CacheProperties.RedisredisProperties=cacheProperties.getRedis(); RedisCacheConfigurationconfig=RedisCacheConfiguration.defaultCacheConfig(); config=config.serializeKeysWith( RedisSerializationContext.SerializationPair.fromSerializer(newStringRedisSerializer())); config=config.serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer(newGenericFastJsonRedisSerializer())); if (redisProperties.getTimeToLive() !=null) { config=config.entryTtl(redisProperties.getTimeToLive()); } if (redisProperties.getKeyPrefix() !=null) { config=config.prefixCacheNameWith(redisProperties.getKeyPrefix()); } if (!redisProperties.isCacheNullValues()) { config=config.disableCachingNullValues(); } if (!redisProperties.isUseKeyPrefix()) { config=config.disableKeyPrefix(); } returnconfig; } }
使用
加上@Cacheable使用
value= {"brand"}, key="#root.methodName") (publicList<Brand>listBrand(intpageNum, intpageSize) { PageHelper.startPage(pageNum, pageSize); returnbaseMapper.selectList(null); }
这样在有缓存的情况下,就直接读取缓存,不会再去查询数据库,从而减轻服务器压力提高性能